JAVA利用HttpClient进行POST请求

目前,要为另一个项目提供接口,接口是用HTTP URL实现的,最初的想法是另一个项目用JQuery post进行请求。

但是,很可能另一个项目是部署在别的机器上,那么就存在跨域问题,而JQuery的post请求是不允许跨域的。

这时,就只能够用HttpClient包进行请求了,同时由于请求的URL是HTTPS的,为了避免需要证书,所以用一个类继承DefaultHttpClient类,忽略校验过程。

package com.hellowin.yl.admin.util.httpUtil;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.rocketmq.common.utils.HttpTinyClient;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

1.写一个利用HttpClient发送post请求的类
public class RequestClientInterface {
    private  CloseableHttpClient httpClient;

    public  RequestClientInterface() {
        // 1 创建HttpClinet,相当于打开浏览器
        this.httpClient = HttpClients.createDefault();
    }

    /**
     * 带参数的post请求
     *
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public  HttpTinyClient.HttpResult doPost(String url, Map<String, Object> map) throws Exception {
        // 声明httpPost请求
         HttpPost httpPost = new HttpPost(url);

        // 判断map不为空
        if (map != null) {
            // 声明存放参数的List集合
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // 遍历map,设置参数到list中
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }

            // 创建form表单对象
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf-8");
            formEntity.setContentType("Content-Type:application/json");

            // 把表单对象设置到httpPost中
            httpPost.setEntity(formEntity);
        }

        // 使用HttpClient发起请求,返回response
        CloseableHttpResponse response = this.httpClient.execute(httpPost);

        // 解析response封装返回对象httpResult
        HttpTinyClient.HttpResult httpResult = null;
        if (response.getEntity() != null) {
            httpResult = new HttpTinyClient.HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), "UTF-8"));
        } else {
            httpResult = new HttpTinyClient.HttpResult(response.getStatusLine().getStatusCode(), "");
        }
        // 返回结果
        return httpResult;
    }
}


2.调用post请求的测试代码
import java.util.HashMap;
import java.util.Map;
    //对接口进行测试
    public class TestMain {
        private String url = "https://192.168.1.101/";
        private String charset = "utf-8";
        private HttpClientUtil httpClientUtil = null;

        public TestMain(){
            httpClientUtil = new HttpClientUtil();
        }

        public void test(){
            String httpOrgCreateTest = url + "httpOrg/create";
            Map<String,String> createMap = new HashMap<String,String>();
            RequestClientInterface clientInterface = new RequestClientInterface();
            createMap.put("orgname","****");
            createMap.put("functionId", "****");
            HttpTinyClient.HttpResult httpResult = clientInterface.doPost(httpOrgCreateTest, createMap);
            System.out.println("result:"+httpResult);
        }

        public static void main(String[] args){
            TestMain main = new TestMain();
            main.test();
        }
    }

参考:https://blog.csdn.net/rongyongfeikai2/article/details/41659353

  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Java利用HttpClient进行POST请求(HTTPS)实例可以通过以下步骤完成: 1. 导入所需的类和包。您需要引入org.apache.http.client包下的HttpClient和HttpPost类,以及org.apache.http.impl.client包下的CloseableHttpClient类。 2. 创建CloseableHttpClient对象。您可以使用HttpClientBuilder类的create()方法来创建一个CloseableHttpClient对象。 3. 创建HttpPost对象并设置URL。您需要创建HttpPost对象,并使用setURI()方法设置要发送请求的URL。 4. 设置请求参数。您可以使用NameValuePair来设置请求参数,然后通过setEntity()方法设置到HttpPost对象中。 5. 执行POST请求并获取响应。使用CloseableHttpClient对象的execute()方法执行POST请求,将HttpPost对象作为参数传递给execute()方法。然后,获取HttpResponse对象并从中提取响应内容。 下面是一个示例代码: ``` import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; public class HttpClientPostExample { public static void main(String[] args) { String url = "https://example.com/post"; // 设置要发送的URL try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { HttpPost httpPost = new HttpPost(url); // 创建HttpPost对象并设置URL List<NameValuePair> params = new ArrayList<>(); // 创建请求参数列表 params.add(new BasicNameValuePair("key1", "value1")); // 设置请求参数 params.add(new BasicNameValuePair("key2", "value2")); httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); // 设置请求参数到HttpPost对象中 HttpResponse httpResponse = httpClient.execute(httpPost); // 执行POST请求并获取响应 if (httpResponse.getStatusLine().getStatusCode() == 200) { // 判断响应状态码 String response = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8); System.out.println("响应内容:" + response); } else { System.out.println("POST请求失败!"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 这个示例展示了如何使用Apache HttpClient进行POST请求,并向请求中添加参数。其中,我们使用了URL编码工具类URLEncodedUtils和EntityUtils来处理请求参数和响应内容。请根据实际情况修改URL和请求参数,并根据需要处理响应结果。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值