Java使用HttpClient调用其他http接口


本文经测试可用,直接创建工具类进行调用即可。

引入依赖

       
            com.alibaba
            fastjson
            1.2.68
        
        
            org.apache.httpcomponents
            httpclient
            4.3.5
        

工具类代码如下:

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.net.SocketTimeoutException;
import java.nio.charset.Charset;

public class HttpClientUtils {
 
    /**
     * 发送HttpClient请求
     */
    public static String sendPost(String requestUrl,String requestParams) {
        JSONObject jb = new JSONObject();
        jb.put("code",0);
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(300 * 1000)
                .setConnectTimeout(300 * 1000)
                .build();
            HttpPost post = new HttpPost(requestUrl);
            post.setConfig(requestConfig);
            post.setHeader("Content-Type","application/json;charset=utf-8");
            /*传键值对
            List list = new ArrayList<>();
            list.add(new BasicNameValuePair("productName", "555"));
            list.add(new BasicNameValuePair("totalFee", "666"));
            HttpEntity entity = new UrlEncodedFormEntity(list);*/
            //传json字符串
            StringEntity postingString = new StringEntity(requestParams,Charset.forName("UTF-8"));
            post.setEntity(postingString);
            HttpResponse response = httpClient.execute(post);
            String content = EntityUtils.toString(response.getEntity());
            System.out.println("接口返回内容为:" + content);
            return content;
        } catch (SocketTimeoutException e) {
           System.out.println("调用接口超时,超时时间:" + 300+ "秒,url:" + requestUrl + ",参数:" + requestParams);
            return jb.toString();
        } catch (Exception e) {
           System.out.println("调用接口失败,url:" + requestUrl + ",参数:" + requestParams);
            return jb.toString();
        }
    }
} 

调用其他项目接口demo

本地项目调用工具类的sendPost方法并传入对应参数

import com.alibaba.fastjson.JSON;
import java.util.HashMap;
import java.util.Map;

public class Test {
    public static void main(String[] args) {

        String requestUrl = "http://localhost:8889/testClient";
        Map map1=new HashMap<>();
        map1.put("name","信梧");
        map1.put("age",1);
        String jsonStr=JSON.toJSONString(map1);
        HttpClientUtils.sendPost(requestUrl,jsonStr );
    }
}

远程项目接口代码

 @ResponseBody
    @RequestMapping(value = "/testClient", method = RequestMethod.POST)
    public String map2xml(@RequestBody String json) {
        System.out.println("接口被调用...");
        System.out.println("接收数据为:"+json);
        HashMap map = new HashMap<>();
        map.put("userName", "张三");
        map.put("age", 10);
        map.put("weight", "60kg");
        return  map.toString();
    }

启动远程项目后,启动本地项目Test类,结果如下:

本地项目

 远程项目

注意:远程项目接收参数用@RequestBody注解 并且接收参数和传递参数时参数类型相同即可,参数名不一样不影响。