HttpClient应用案例post&get方法

本文主要是列举出了HttpClient的简单使用方法,一个是post方法,另一个是get方法。

这里所使用的是HttpClient4.5.jar

以及使用了JSON-lib-2.1.jar

有兴趣的朋友可以在CSDN里搜一下,可以找到

首先post方法,这边我希望传递一个实体类给服务端,所以引用了JSON得方式去传递

先将实体类转换成JSON,再将JSON转换成String字符串型,通过HTTP发送:

package com.HTTPtransfer.test.httpClient;

import java.io.IOException;
import java.nio.charset.Charset;

import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClientTool {

    /**
     * post请求传输String参数
     * Content-type:application/json
     * 
     * @param url
     * url地址
     * @param fileReport
     * 文件报表对象
     * @param responseStr
     * 不需要返回结果
     * @return
     */
    public static String httpPost(String url, FileReport fileReport) {
        // POST请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject json = JSONObject.fromObject(fileReport);
        HttpPost httpPost = new HttpPost(url);
        String responseStr = null;
        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
        httpPost.setConfig(requestConfig);
        try {
            if (null != json.toString()) {
                StringEntity entity = new StringEntity(json.toString(), Charset.forName("UTF-8"));
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                try {
                    // 读取服务器返回过来的json字符串数据
                    responseStr = EntityUtils.toString(result.getEntity(), "utf-8");
                    System.out.println(responseStr);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }
        return responseStr;
    }

接下来是GET方法,与POST方法不同的是GET方法是将传递的参数放到访问的URL后;
下面这段代码的红色部分就是所要传递的参数:

    /**
     * 发送get请求
     * 
     * @param url
     * 路径
     * @return
     */
    public static String httpGet(String url, FileReport fileReport) {
        // GET请求返回结果
        CloseableHttpClient client = HttpClients.createDefault();
        url = url + "/?fileCode=" + fileReport.getFileCode();
        url = url + "&bizDate=" + fileReport.getBizDate();
        HttpGet httpGet = new HttpGet(url);
        String responseStr = null;
        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
        httpGet.setConfig(requestConfig);
        try {
            CloseableHttpResponse response = client.execute(httpGet);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                responseStr = EntityUtils.toString(entity, "utf-8");
                System.out.println(responseStr);
            } else {

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpGet.releaseConnection();
        }
        return responseStr;
    }

}

在介绍完如何通过HttpClient来参数之后,还有一篇关于在Spring框架中接收HttpClient的POST和GET请求的方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基本的Apache HttpClient Post案例: ```java import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; public class HttpClientPostExample { public static void main(String[] args) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost("http://localhost:8080/api/post-example"); // 设置请求头 httpPost.setHeader("Content-Type", "application/json"); // 设置请求体 String json = "{\"name\": \"John\", \"age\": 30}"; StringEntity entity = new StringEntity(json); httpPost.setEntity(entity); // 发送请求 CloseableHttpResponse httpResponse = httpClient.execute(httpPost); try { // 获取响应体 HttpEntity httpEntity = httpResponse.getEntity(); String responseJson = EntityUtils.toString(httpEntity); System.out.println(responseJson); } finally { httpResponse.close(); } } finally { httpClient.close(); } } } ``` 在这个例子中,我们首先创建了一个HttpClient对象。然后,我们创建了一个HttpPost对象,并设置了请求头和请求体。最后,我们发送请求并获取响应体。 请注意,我们在try-with-resources块中使用了CloseableHttpResponse和CloseableHttpClient,以确保它们在使用后被关闭。此外,我们还使用了Apache HttpClient的EntityUtils类来处理响应体。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值