HttpClient简易使用

工作中用到HttpClient发送一个请求到https服务器。携带auth-token和csv文件。现在此做一个小结。

版本4.x.x

  • httpcore:对HTTP协议的基础封装的一套组件。
  • httpclient:基于httpcore的一个HTTP客户端实现。
  • httpmime:包括了所有的MIME类型,便于解析。

MAVEN依赖



    org.apache.httpcomponents
    httpcore
    4.x




    org.apache.httpcomponents
    httpclient
    4.x




    org.apache.httpcomponents
    httpmime
    4.x

实现

CloseableHttpClient httpClient = HttpClients.createDefault();
this.localfilename = "E:\\CSVDir\\" + localFile;
serverDirectory = "/" + userName +"/";

try {
    HttpPost httpPost = new HttpPost(server);

//    String redisKey = "ftp.dicostapartners.com$Hrz8";
//    userToken = uploadRedisDao.getUserToken(redisKey);

//    // string转成JSONObject
//    JSONObject token = JSONObject.parseObject(userToken);
//    String tok = token.getString("Authorization");

    // 设置请求头
    httpPost.addHeader("Authorization", tok);

    // 设置form data
    StringBody request = new StringBody("upload", ContentType.TEXT_PLAIN);
    StringBody targetdirectory = new StringBody(serverDirectory, ContentType.TEXT_PLAIN);
    FileBody upload = new FileBody(new File(this.localfilename));

    HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("request", request)
            .addPart("targetdirectory", targetdirectory).addPart("upload", upload).build();
    httpPost.setEntity(reqEntity);

    // httpClient对象执行post请求,并返回响应参数对象
    CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
    // 从响应对象中获取响应内容
    HttpEntity resEntity = httpResponse.getEntity();
    logger.info(EntityUtils.toString(resEntity));
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        // 关闭资源
        if (null != httpResponse) {
            httpResponse.close();
        }
        if (null != httpClient) {
            httpClient.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

网上一个很好的httpclient系列可供参考 https://www.cnblogs.com/myitnews/p/12194948.html

你可能感兴趣的:(工作)