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();
        }
    }

发布了39 篇原创文章 · 获赞 8 · 访问量 3450

猜你喜欢

转载自blog.csdn.net/qq_41555278/article/details/90056669