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;
}
}
在日常的編碼過程中,我們難免會遇到跨域調用接口的問題,可能調用的方法有很多,這裡我介紹的是使用httpClient拉進行接口的調用,于是我封裝了httpClientUtils,這個工具類,适用于,傳入json資料,傳回json資料。