• 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注解 并且接收参数和传递参数时参数类型相同即可,参数名不一样不影响。

  • 相关阅读:
    Flexiframe在SWF中嵌入网页的组件(推荐)
    Flash as3 未在基类中找到默认的构造函数
    flex4 FLVPlayer回去弄下
    SWF 文件不能访问本地资源 只有仅限于文件系统的 SWF 文件和可信的本地 SWF 文件可以访问本地资源[转载]
    本人写的AS3中级程序员面试题
    绕开AS3安全沙箱,跨域加载SWF
    怎样去掉ApplicationControlBar的阴影
    叫你认清这个世界(for编程语言)
    资深HR八年招聘用人心得 给毕业生的实用求职建议
    本人写的AS3高级程序员面试文档(未完成)
  • 原文地址:https://www.cnblogs.com/wffzk/p/16271104.html
Copyright © 2020-2023  润新知