您的位置:首页 > 编程语言 > Java开发

java通过url调用远程接口返回json数据,有用户名和密码验证

2017-12-15 18:41 1071 查看
最近有需要调用url远程接口来获取返回值,还有用户名和密码验证

使用http请求来获取接口返回值,代码如下

package com.kp.module;

import com.kp.constant.ServerConstant;
import java.util.Base64;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Tesalkt {
public static void main(String[] args) throws Exception {

StringBuffer buffer = new StringBuffer();
HttpURLConnection httpConn = null;
BufferedReader reader = null;
try {
//url远程接口
String strURL = ServerConstant.SERVER_RUNTIME_INTERFACE+"118.31.11.213";
//用户名
String username = ServerConstant.SERVER_RUNTIME_USRENAME;
//密码
String password = ServerConstant.SERVER_RUNTIME_PASSWORD;
//原先使用的时com.sun.org.apache.xml.internal.security.utils.Base64,这个包虽然在jdk中,
//但并不是标准的包,所以在gradle编译打包时总是无法引入改包,所以不用这个包
// String author = "Basic " + Base64.encode((username+":"+ password).getBytes());
//使用jdk1.8中的java.util.Base64来对字符串加密
String author = "Basic " + Base64.getEncoder().encodeToString((username+":"+ password).getBytes());

URL url = new URL(strURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("Authorization", author);
httpConn.connect();

reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpConn != null) {
httpConn.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("接口返回值:"+buffer.toString());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: