java实现HTTP发送请求

2 篇文章 0 订阅
2 篇文章 0 订阅

JAVA实现http接口调用

Get请求

Get请求比较简单,代码如下:

/**
     * 返回API调用结果
     *
     * @param APIName 接口在api.properties中的名称
     * @param params  访问api所需的参数及参数值
     * @return 此处返回的是JSON格式的数据
     */
    public static String linkUrl(String uri, String APIName, Map<String, String> params) {
        String content = "";
        //请求结果
        CloseableHttpResponse response = null;
        //实例化httpclient
        CloseableHttpClient httpclient = HttpClients.createDefault();

        try {
            //http://192.168.1.107/user/list
            String api = generateUrl(uri,APIName); 
            //构造url请求
            if (params != null && params.size() > 0) {
                api += "?";
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    api += entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), encoding) + "&";
                }
                api = api.substring(0, api.length() - 1);
            }
            //实例化get方法
            HttpGet httpget = new HttpGet(api);
            //执行get请求
            response = httpclient.execute(httpget);
            if (response.getStatusLine().getStatusCode() == 200) {
                content = EntityUtils.toString(response.getEntity(), encoding);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }

POST请求

  1. 参数为表单格式
 /**
     *功能描述
     * @Title
     * @description :  post请求
     * @author  yanbo
     * @create  2019/5/9 12:20
     * @param * @param: url
     * @param: map
     * @param: encoding
     * @return java.lang.String
     */
    public static String sendPost(String uri, String APIName,Map<String, String> map) throws ParseException, IOException {

        String body = "";
        //http://192.168.1.107/user/list
        String url = generateUrl(uri,APIName);
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);

        //装填参数
        List<NameValuePair> nvps = new ArrayList<>();
        if (map != null) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        //设置参数到请求对象中
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));

//        System.out.println("请求地址:" + url);
//        System.out.println("请求参数:" + nvps.toString());

        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //执行请求操作,并拿到结果(同步阻塞)
        CloseableHttpResponse response = client.execute(httpPost);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return body;
    }
  1. 参数为json格式
public static JSONObject doPost(String url, String json) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        try {
            StringEntity s = new StringEntity(json);
            s.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            s.setContentType("application/json");
            post.setEntity(s);
            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = res.getEntity();
                // 返回json格式:
                String result = EntityUtils.toString(entity,"UTF-8");
                response = JSONObject.fromObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return response;
    }

上面的代码用的 HttpEntity是 StringEntity, 如果你要请求的接口没有给你指定,而且返回结果和你用postman等工具测试结果返回不一样,那么可能是这个entity的编码有问题了,可以设置编码,
new StringEntityURLEncoder.encode(JSON.toJSONString(requestMap), "UTF-8"))
如果编码没问题了,但是对方那里判断的结果,和你参数应该正常的判断结果不一致,也有可能是序列化协议不匹配,建议试一试下面的方式:

   ByteArrayEntity entity = null;
   entity = new ByteArrayEntity(requestBody.getBytes("UTF-8"));
   entity.setContentType("application/json");
   httpPost.setEntity(entity);

如果请求的是 https,报什么 javax.net.ssl.SSLException: Certificate for <msgo.10010.com> doesn't match any of the subject alternative names这种错误,那么需要你的HTTPClient要这样写:

 SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(
                SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), NoopHostnameVerifier.INSTANCE);
        CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(scsf).build();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值