HttpURLConnection发送basic auth的post与get请求
package com.skyable.account.system.util;
import com.alibaba.fastjson.JSONObject;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
public class HttpURLConnectionUtil {
@Value("${***.***.***}")
public static String authUsername;
@Value("${***.***.***}")
public static String authPassword;
public static String httpURLConnectionGet(String strUrl){
BufferedReader in = null;
String username = authUsername;
String password = authPassword;
String auth = username+":"+password;
byte[] rel = Base64.encodeBase64(auth.getBytes());
String res = new String(rel);
try {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(30000);
conn.setRequestProperty("Authorization","Basic " + res);
conn.setReadTimeout(30000);
conn.setDoOutput(false);
conn.setDoInput(true);
String result = "";
int code = conn.getResponseCode();
if(code == 200){
in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
in.close();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String httpURLConnectionPost(String strUrl, Map params){
String jsonString = JSONObject.toJSONString(params);
PrintWriter out = null;
BufferedReader in = null;
String username = authUsername;
String password = authPassword;
String auth = username+":"+password;
byte[] rel = Base64.encodeBase64(auth.getBytes());
String res = new String(rel);
try {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-type", "application/json");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestMethod("POST");
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setRequestProperty("Authorization","Basic " + res);
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
out.print(jsonString);
out.flush();
out.close();
String result = "";
int code = conn.getResponseCode();
if(code == 200){
in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
in.close();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}