java使用Httpclient发送post、get和delete请求

一、Httpclient发送post

 public static JSONObject post(String url, JSONObject json, BaseReqPojo headers) throws Exception {
        JSONObject response = null;
        BufferedReader bufferedReader = null;
        StringBuilder entityStringBuilder = new StringBuilder();
        try {
            HttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            post.setEntity(new StringEntity(json.toString(), "UTF-8"));

            LOGGER.info("客户端请求报文:" + s.toString());

            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = res.getEntity();
                if (entity != null) {
                    bufferedReader = new BufferedReader
                            (new InputStreamReader(entity.getContent(), "UTF-8"), 8 * 1024);
                    String line = null;
                    while ((line = bufferedReader.readLine()) != null) {
                        entityStringBuilder.append(line);
                    }
                    LOGGER.info("客户端获取响应报文:" + entityStringBuilder.toString());
                    response = JSONObject.parseObject(entityStringBuilder.toString());
                }
            } else {
                LOGGER.info("连接失败:" + res);
            }
        } catch (Exception e) {
            throw new Exception(e);
        }
        return response;
    }

二、Httpclient发送get

public static JSONObject get(String url, BaseReqPojo headers) throws Exception{
        JSONObject response = new JSONObject();
        try {
            HttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);

            httpGet.setHeader("Content-Type", "application/json");
            
            HttpResponse httpResponse = httpClient.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) {
                LOGGER.info("客户端获取响应报文header->[" + httpResponse + "]");
                HttpEntity entity = httpResponse.getEntity();
                if (entity != null) {
                    StringBuilder entityStringBuilder = new StringBuilder();
                    BufferedReader bufferedReader = new BufferedReader
                            (new InputStreamReader(entity.getContent(), "UTF-8"), 8 * 1024);
                    String line = null;
                    while ((line = bufferedReader.readLine()) != null) {
                        entityStringBuilder.append(line);
                    }
                    LOGGER.info("客户端获取响应报文:" + entityStringBuilder.toString());
                    Object obj = JSONObject.parse(entityStringBuilder.toString());
                    if (obj instanceof JSONArray) {
                        response.put("list", obj);
                    } else {
                        response = (JSONObject) obj;
                    }
                    // 返回的报文体为空时
                    if (response == null) {
                        response = new JSONObject();
                    }
                }
            }
        } catch (Exception e) {
            throw new Exception(e);
        }
        return response;
    }

三、Httpclient发送delete

1.由于HttpDelete不能添加参数,需要复写HttpDelete

public class MyHttpDelete extends HttpEntityEnclosingRequestBase {

    public static final String METHOD_NAME = "DELETE";

    public String getMethod() {
        return METHOD_NAME;
    }

    public MyHttpDelete(final String uri) {
        super();
        setURI(URI.create(uri));
    }

    public MyHttpDelete(final URI uri) {
        super();
        setURI(uri);
    }

    public MyHttpDelete() {
        super();
    }
}

2.发送delete请求

public static JSONObject delete(String url, JSONObject json) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        MyHttpDelete httpDelete = new MyHttpDelete(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(10000).build();
        httpDelete.setConfig(requestConfig);
        httpDelete.setHeader("Content-type", "application/json");
        httpDelete.setHeader("DataEncoding", "UTF-8");

        CloseableHttpResponse httpResponse = null;
        try {
            httpDelete.setEntity(new StringEntity(JSON.toJSONString(json),"UTF-8"));
           
            httpResponse = httpClient.execute(httpDelete);
            HttpEntity entity = httpResponse.getEntity();
            StringBuilder entityStringBuilder = new StringBuilder();
            BufferedReader bufferedReader = new BufferedReader
                    (new InputStreamReader(entity.getContent(), "UTF-8"), 8 * 1024);
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                entityStringBuilder.append(line);
            }
            LOGGER.info("客户端获取响应报文:" + entityStringBuilder.toString());
            return JSONObject.parseObject(entityStringBuilder.toString());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
HttpClient是一个用于发送HTTP请求的开源框架,可以通过它发送GET、POST、PUT、DELETE等各种类型的请求。 如果需要使用HttpClient发送HTTPS的POST请求,需要对HttpClient进行配置,以确保安全性。 首先,需要创建一个SSL连接,用于发送HTTPS请求。可以通过创建一个SSL连接工厂来实现,这个工厂会使用信任的CA证书来验证目标服务器的身份。 接下来,创建一个HttpClient实例,并设置SSL连接工厂。 然后,创建一个HttpPost对象,设置请求的URL和请求参数。 接着,设置请求头,包括标识请求类型为POST、设置Content-Type为application/x-www-form-urlencoded等。 最后,使用HttpClient的execute方法执行POST请求,并获取返回的响应。 下面是一个示例代码: ``` 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.ssl.SSLContextBuilder; import org.apache.http.ssl.TrustStrategy; import org.apache.http.util.EntityUtils; import javax.net.ssl.SSLContext; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; public class HttpsPostExample { public static void main(String[] args) throws Exception { // 创建SSL连接工厂 SSLContext sslContext = SSLContextBuilder.create() .loadTrustMaterial(new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; // 所有证书都被信任 } }) .build(); // 创建HttpClient实例,并设置SSL连接工厂 CloseableHttpClient httpClient = HttpClients.custom() .setSSLContext(sslContext) .build(); // 创建HttpPost对象,并设置URL和请求参数 HttpPost httpPost = new HttpPost("https://example.com"); String requestBody = "param1=value1&param2=value2"; httpPost.setEntity(new StringEntity(requestBody)); // 设置请求httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); // 发送POST请求,并获取响应 CloseableHttpResponse response = httpClient.execute(httpPost); String responseBody = EntityUtils.toString(response.getEntity()); // 输出响应结果 System.out.println(responseBody); // 关闭连接 response.close(); httpClient.close(); } } ``` 以上就是使用HttpClient发送HTTPS的POST请求的方法。通过SSL连接工厂的设置,可以确保请求的安全性。在实际使用中,可以根据需要设置请求参数、请求头等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杭小飞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值