發現用JDK原生的POST請求比Apache的請求要快。記錄一下apache
public static JSONObject sendPost(String postUrl, String strReqJsonStr) throws Exception {
JSONObject respJson = null;
HttpURLConnection httpURLConnection = null;
BufferedReader in = null;
PrintWriter out = null;
try {
URL url = new URL(postUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Accept", "application/json");
httpURLConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
// 發送POST請求參數
out = new PrintWriter(httpURLConnection.getOutputStream());
out.write(strReqJsonStr);
out.flush();json
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
StringBuffer content = new StringBuffer();
String tempStr = null;
in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
while ((tempStr = in.readLine()) != null) {
content.append(tempStr);
}app
respJson = JSON.parseObject(content.toString());
}
} catch (Exception e) {
throw new Exception(e.toString());
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
} catch (Exception e) {
}
}
System.out.println(respJson);
return respJson;
}post
2. apache的包性能
public static boolean httpPostWithJson(JSONObject jsonObj) {
boolean isSuccess = false;url
HttpPost post = null;
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClients.createDefault();utf-8
// 設置超時時間get
post = new HttpPost(URL);
// 構造消息頭
post.setHeader("Content-type", "application/json; charset=utf-8");
post.setHeader("Connection", "Close");
// 構建消息實體
StringEntity entity = new StringEntity(jsonObj.toString(), Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
// 發送Json格式的數據請求
entity.setContentType("application/json");
post.setEntity(entity);it
HttpResponse response = httpClient.execute(post);io
Header[] headers = response.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
Header header = headers[i];
System.out.println("h--" + header);
}
System.out.println("====================");
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
try {
System.out.println(EntityUtils.toString(httpEntity));
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
isSuccess = false;
} finally {
if (post != null) {
try {
post.releaseConnection();
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return isSuccess;
}
性能比較
apache 耗時:964
JDK 耗時: 70