HttpClient 跨域请求

仅供参考

HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
HttpClient的主要功能:
(1)实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)
(2)支持自动转向
(3)支持 HTTPS 协议
(4)支持代理服务器等
要知道更多详细的功能可以参见 HttpClient 的主页:
httpClient中文网:link
httpClient 英文:link

实例

1、首先引入HttpClient jar包

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>

2、只举例POST
选择jar包的时候,要看仔细

public void HttpTest() throws Exception {//测试远程访问接口
        String Url = "http://地址:端口/接口";//设置远程访问路径
        //httpClient 来自:import org.apache.http.impl.client.CloseableHttpClient;
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(Url);//使用post进行访问 来自:import org.apache.http.client.methods.HttpPost;
        InsuranceOrderNo insuranceOrderNo1 = new InsuranceOrderNo();//需要发送的数据,我这里是以对象的形式
            StringEntity stringEntity = new StringEntity(JSONObject.fromObject(insuranceOrderNo1).toString()); //声明一个String实体 来自:import org.apache.http.entity.StringEntity; 主要用于完善请求
            stringEntity.setContentEncoding("编码格式");
            stringEntity.setContentType("访问格式");
            post.setEntity(stringEntity);
            System.out.println("post访问路径" + post.getURI());
            HttpResponse httpResponse = httpClient.execute(post); //执行请求 来自:import org.apache.http.HttpResponse;
            String result = EntityUtils.toString(httpResponse.getEntity());//
            System.out.println("打印result:"+JSONObject.fromObject(result).toString())//因为我这返回的是json      
    }

亲测有效哦!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值