• Java使用HttpClient调用其他http接口


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

    引入依赖

           <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.68</version>
            </dependency>
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.3.5</version>
            </dependency>

    工具类代码如下:

    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<BasicNameValuePair> 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<String,Object> 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<Object, Object> map = new HashMap<>();
            map.put("userName", "张三");
            map.put("age", 10);
            map.put("weight", "60kg");
            return  map.toString();
        }

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

    本地项目

     远程项目

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

  • 相关阅读:
    Webpack中publicPath设置
    忘记Mysql的root密码怎么办?
    Visual Studio 2015上安装Entity Framework Power Tools
    Ubuntu下安装中文输入法
    Ubuntu如何选择更新源
    Orchard中如何配置远端发布
    .Net缓存管理框架CacheManager
    全新的membership框架Asp.net Identity(2)——绕不过的Claims
    全新的membership框架Asp.net Identity(1)——.Net membership的历史
    泛型使用中,解决类型转换问题
  • 原文地址:https://www.cnblogs.com/wffzk/p/16271104.html
Copyright © 2020-2023  润新知