随笔 - 57  文章 - 0  评论 - 3  阅读 - 12万 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package httpclient.httpclient;
 
import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
 
public class HttpClientUtil {
    public void testPost() {
        //1.创建客户端访问服务器的httpclient对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //2.定义请求的url
        String url = "https://XXX.XXX.com/NC1000001";
        //3.以请求的连接地址创建get/post请求对象
        HttpPost post = new HttpPost(url);
        //如果有header请求,添加header请求
        post.addHeader("x-api-key", "XXX");
        post.addHeader("x-lang", "en-US");
        try {
            //4.向服务器发送请求,并获取返回数据
            CloseableHttpResponse response = httpClient.execute(post);
            //获取返回的所有headers
            Header[] headers = response.getAllHeaders();
            for (Header header : headers) {
                System.out.println(header);
            }
            //获取返回的状态
            int status = response.getStatusLine().getStatusCode();
            System.out.println(status);
            //获取HttpEntity消息载体对象
            HttpEntity entity = response.getEntity();
            // EntityUtils中的toString()方法转换服务器的响应数据
            String str = EntityUtils.toString(entity, "utf-8");
            System.out.println("服务器的响应是:" + str);
            //5.关闭连接
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) {
        HttpClientUtil util = new HttpClientUtil();
        util.testPost();
    }
}

运行结果:

Date: Wed, 06 Sep 2017 09:49:39 GMT
Server: Apache/2.4.7 (Ubuntu)
Cache-Control: no-cache, private
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 59
Content-Length: 150
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: application/json
200
服务器的响应是:{"id":1000001,"tracking_id":"NC1000001"}

posted on   Jourly  阅读(3674)  评论(0编辑  收藏  举报
编辑推荐:
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
· .NET 9 new features-C#13新的锁类型和语义
阅读排行:
· Spring AI + Ollama 实现 deepseek-r1 的API服务和调用
· 《HelloGitHub》第 106 期
· 数据库服务器 SQL Server 版本升级公告
· 深入理解Mybatis分库分表执行原理
· 使用 Dify + LLM 构建精确任务处理应用
点击右上角即可分享
微信分享提示