使用httpClient跨域呼叫介面
阿新 • • 發佈:2019-01-24
在日常的編碼過程中,我們難免會遇到跨域呼叫介面的問題,可能呼叫的方法有很多,這裡我介紹的是使用httpClient拉進行介面的呼叫,於是我封裝了httpClientUtils,這個工具類,適用於,傳入json資料,返回json資料。import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import net.sf.json.JSONObject; public class HttpClientUtils { public static String doPost(String Url,Map<String, Object> resultMap) throws IOException{ //建立一個httpclient物件 CloseableHttpClient client=HttpClients.createDefault(); //建立一個post物件 HttpPost post=new HttpPost(Url); //設定引數 List<NameValuePair> nvps = new ArrayList<NameValuePair>(); JSONObject jsonObject = JSONObject.fromObject(resultMap); String param=jsonObject.toString(); nvps.add(new BasicNameValuePair("params",param)); post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8")); CloseableHttpResponse response =client.execute(post); //判斷返回的狀態 StatusLine status = response.getStatusLine(); int state = status.getStatusCode(); if (state == HttpStatus.SC_OK) { HttpEntity responseEntity = response.getEntity(); String json = EntityUtils.toString(responseEntity); System.out.println("狀態碼:"+state); response.close(); client.close(); return json; } response.close(); client.close(); return null; } }