java 接口请求

程序员零花钱码上赚

 

 


   接口post请求 body中传输数据
     
    public static String sendHttpPost(String url, String body) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(body));

        CloseableHttpResponse response = httpClient.execute(httpPost);
        System.out.println(response.getStatusLine().getStatusCode() + "\n");
        HttpEntity entity = response.getEntity();
        String responseContent = EntityUtils.toString(entity, "UTF-8"); 
        System.out.println(responseContent);

        response.close();
        httpClient.close();
        return responseContent;
        }

   获取request中的数据  可以取得post请求 body中传输的数据

 public static String getBody(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        try {
            String line = null;
            InputStream inputStream;
            inputStream = request.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            //reader = request.getReader();
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            in.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }


    private final static CloseableHttpClient client = HttpClients.createDefault();
    private final static RequestConfig config = RequestConfig.custom().setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).setSocketTimeout(5000).build();

    post请求接口(url后面接数据)
    public final static JSONObject post(final String url,final Map<String, String> params) {
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        post.setConfig(config);
        try {
            if(params!=null) {
                List<NameValuePair> list = Lists.newArrayList();
                params.forEach((k,v)->{
                    list.add(new BasicNameValuePair(k, v));
                });
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list,"UTF-8");
                post.setEntity(formEntity);
            }
            HttpResponse response = client.execute(post);
            String result = EntityUtils.toString(response.getEntity(), "UTF-8");
            return JSONObject.fromObject(result);
        } catch (Exception e) {
            throw new RuntimeException("POST("+url+")请求失败");
        }finally {
            post.releaseConnection();
        }
    }
    get请求接口(uri后面截数据)
    public final static JSONObject get(final String url,final Map<String, String> params) {
        StringBuffer sb = new StringBuffer(url).append("?myparam=1");
        if(params!=null) {
            params.forEach((k,v)->{
                sb.append("&").append(k).append("=").append(v);
            });
        }
        HttpGet get = new HttpGet(sb.toString().replaceAll(" ", "%20"));
        get.setConfig(config);
        try {
            HttpResponse response = client.execute(get);
            String result = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println(result);
            return JSONObject.fromObject(result);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(url);
            throw new RuntimeException("GET("+url+")请求失败");
        }finally {
            get.releaseConnection();
        }
    }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值