使用HttpClient進行http請求(一切ajax請求都改造成HttpClient方式)
1.專案中最近需要在後端訪問外部系統介面,原本在前端可以用ajax傳送的訪問請求要改造成後端http訪問,於是在網上搜了一下相關資料,最終採用了HttpClient。
2.以下列出的是 HttpClient 提供的主要的功能,要知道更多詳細的功能可以參見 HttpClient 的主頁。
(1)實現了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)
(2)支援自動轉向
(3)支援 HTTPS 協議
(4)支援代理伺服器
3.演示程式碼如下:
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.sf.json.JSONObject;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpClientUtil {
/**
* 使用HttpClient進行http get請求
*/
public static void get(String url) {
/**
* client和response需要關閉資源
*/
// 建立client,放入try()中自動釋放,不需要finally
try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
// 執行得到response
try (CloseableHttpResponse response = client.execute(new HttpGet(url))) {
// 獲取statusCode
Integer statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (entity != null) {
// body
String bodyAsString = EntityUtils.toString(entity);
// Media Type
String contentMimeType = ContentType.getOrDefault(entity).getMimeType();
// head
Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
// 輸出
System.out.println("statusCode:" + statusCode);
System.out.println("contentMinmeType:" + contentMimeType);
System.out.println("body:" + bodyAsString);
System.out.println("head" + headers);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 使用HttpClient進行http post請求
* @param url 請求url
* @param params 請求引數
* @return
*/
public static JSONObject post(String url,List<NameValuePair> params) {
JSONObject ret = new JSONObject();
// 建立client
try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
//新增請求url
HttpPost postRequest = new HttpPost(url);
// 新增請求引數
/* List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("_SRVNAME", "server.app.loginAPI"));
params.add(new BasicNameValuePair("_SRVMETHOD", "verifyAccount"));
params.add(new BasicNameValuePair("_DATA", str));*/
postRequest.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
// 執行並獲取返回結果到response
try (CloseableHttpResponse response = client.execute(postRequest)) {
// 獲取statusCode
Integer statusCode = response.getStatusLine().getStatusCode();
// Media Type
String contentMimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();
// body
String bodyAsString = EntityUtils.toString(response.getEntity());
// head
Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
System.out.println("return time:" + new Date());
System.out.println("statusCode:" + statusCode);
System.out.println("contentMinmeType:" + contentMimeType);
System.out.println("body:" + bodyAsString);
System.out.println("head" + headers);
ret = JSONObject.fromObject(bodyAsString);
}
} catch (IOException e) {
e.printStackTrace();
}
return ret;
}
public static void main(String[] args) {
System.out.println("----------------開始--------------------");
//根據外部系統定義的介面組織介面需要的引數
JSONObject jo = new JSONObject();
JSONObject jo2 = new JSONObject();
jo2.put("type", "01");
jo2.put("loginname", "admin");
jo2.put("password", "123456");
jo.put("form", jo2);
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("_SRVNAME", "server.app.loginAPI"));
params.add(new BasicNameValuePair("_SRVMETHOD", "verifyAccount"));
params.add(new BasicNameValuePair("_DATA", jo.toString()));
String url = "http://192.168.81.107:8080/nl-app-lx/wdk?action=wdk.pub&method=call_service&ajaxparam="+new Date().getTime();
//呼叫工具方法
JSONObject ret = post(url,params);
//輸出返回資料
System.out.println(ret.optString("code"));
System.out.println(ret.optString("desc"));
JSONObject result = ret.optJSONObject("result");
System.out.println(result.optString("account_id"));
System.out.println(result.optString("account_name"));
System.out.println(result.optString("user_name"));
}
}//程式碼演示結束
4.main方法RUN AS跑起來後,控制檯輸出的資訊如下所示: