/**
* 构造Basic Auth认证头信息
*
* @return
*/
private static String getHeader() {
String auth = APP_KEY + ":" + SECRET_KEY;
//进行加密
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
String authHeader = "Basic " + new String(encodedAuth);
return authHeader;
}
public static void main(String[] args) {
//Basic Auth认证的请求
HttpURLConnection connection = null;
try {
URL postUrl = new URL(URL);
connection = (HttpURLConnection) postUrl.openConnection();
//write header
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("authorization", getHeader());
//set timeout
connection.setConnectTimeout(1000 * 5);
connection.setReadTimeout(1000 * 10);
//设置是否输出,默认是false
connection.setDoOutput(false);
//设置是否读入,默认是true
connection.setDoInput(true);
//write body post
//获取字符输出流
// DataOutputStream out = new DataOutputStream(connection.getOutputStream());
//发送请求参数
// out.write("".toString().getBytes());
//刷新输出流
// out.flush();
//关闭输出流
// out.close();
// read response
if (connection.getResponseCode()==200){
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println("line:"+line);
}
reader.close();
}else{
System.out.println("请求失败:"+connection.getResponseCode());
}
}catch (Exception e) {
// TODO: handle exception
if(connection!=null){
connection.disconnect();
}
}finally {
connection.disconnect();
}
}
HttpURLConnection POST/GET Basic Auth认证请求
最新推荐文章于 2024-07-30 03:18:53 发布