• httpClient 4.x post get方法


    public static String doPost(String url, String encoding, String contentType, String sendData)

    throws Exception {

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    CloseableHttpClient httpclient = httpClientBuilder.build();

    HttpPost httppost = new HttpPost(url);

    StringEntity myEntity = new StringEntity(sendData, encoding);

    myEntity.setContentType(contentType);

    httppost.setEntity(myEntity);

    HttpResponse response = httpclient.execute(httppost);

    HttpEntity resEntity = response.getEntity();

    InputStreamReader reader = new InputStreamReader(resEntity.getContent(), encoding);

    char[] buff = new char['Ѐ'];

     

    StringBuilder sb = new StringBuilder();

    int length;

    while ((length = reader.read(buff)) != -1) {

    sb.append(new String(buff, 0, length));

    }

    httpclient.close();

    return sb.toString();

    }

     

    public static void requestGet(String urlWithParams) throws Exception {

    CloseableHttpClient httpclient = HttpClientBuilder.create().build();

     

    // HttpGet httpget = new HttpGet("http://www.baidu.com/");

    HttpGet httpget = new HttpGet(urlWithParams);

     

    // 配置请求的超时设置

    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5000).setConnectTimeout(5000)

    .setSocketTimeout(5000).build();

    httpget.setConfig(requestConfig);

     

    CloseableHttpResponse response = httpclient.execute(httpget);

    System.out.println("StatusCode -> " + response.getStatusLine().getStatusCode());

     

    HttpEntity entity = response.getEntity();

    String jsonStr = EntityUtils.toString(entity);// , "utf-8");

    System.out.println(jsonStr);

     

    httpget.releaseConnection();

    }

  • 相关阅读:
    day16作业 后台管理
    华为园区网实验
    静态路由与思科的区别
    JUnit 两日游
    SQL语句学习积累·数据的操作
    僵固式思维 OR 成长式思维
    压测噩梦后的小感想
    跌跌撞撞的三年
    Linux命令累积
    LoadRunner 学习(基础一)
  • 原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/5796710.html
Copyright © 2020-2023  润新知