参考:http://hc.apache.org/httpclient-3.x/tutorial.html
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL; @Component
public class HttpClientUtil {
private static CloseableHttpClient httpClient = HttpClients.createDefault(); private static String ADDRESS; public static String getAuthorization() {
String url = "http://" + ADDRESS + "/login";
String data = "{\"username\": \"username\",\"password\": \"password\"}";
HttpURLConnection connection=null;
try {
URL server = new URL(url);
connection = (HttpURLConnection)server.openConnection();
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-Type","application/json;charset=utf-8");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(5*1000);
connection.setReadTimeout(10*1000);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.write(data.toString().getBytes("UTF-8"));
wr.flush ();
wr.close (); String Authorization =connection.getHeaderField("Authorization");
return Authorization;
} catch (Exception e){
e.printStackTrace();
} finally{
if(connection != null ){
connection.disconnect();
}
}
return null;
} public static String post(String url, String body) {
String auth = getAuthorization();
if (auth == null) {
return null;
} HttpPost httpPost = new HttpPost("http://" + ADDRESS + url);
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8");
httpPost.setHeader("Accept", "application/json;charset=UTF-8");
httpPost.setHeader("Authorization", auth); CloseableHttpResponse response2 = null;
try {
StringEntity entity = new StringEntity(body, "utf-8");
System.out.println("request = " + body); httpPost.setEntity(entity); response2 = httpClient.execute(httpPost);
System.out.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
String responseStr = new String(IOUtils.toByteArray(entity2.getContent()));
System.out.println("response = " + responseStr); return responseStr;
} catch(Exception e) {
e.printStackTrace();
return null;
} finally {
if (response2 != null) {
try {
response2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} @Value("${interface.address}")
public void setAddress(String address) {
ADDRESS = address;
}
}