天天看点

使用httpClient跨域调用接口

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数据。