Post with HttpClient
Apache HttpClient是Java中经常使用的Http Client,总结下HttpClient4中经常使用的post请求用法。
1 Basic Post
使用2个参数进行post请求:
@Test public void whenPostRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://www.example.com"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("username", "John")); params.add(new BasicNameValuePair("password", "pass")); httpPost.setEntity(new UrlEncodedFormEntity(params)); CloseableHttpResponse response = client.execute(httpPost); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); client.close(); }
2 POST with Authorization
使用Post进行Basic Authentication credentials验证:
@Test public void whenPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException, AuthenticationException { CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://www.example.com"); httpPost.setEntity(new StringEntity("test post")); UsernamePasswordCredentials creds = new UsernamePasswordCredentials("John", "pass"); httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null)); CloseableHttpResponse response = client.execute(httpPost); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); client.close(); }
3 Post with JSON
使用JSON body进行post请求:
@Test public void whenPostJsonUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://www.example.com"); String json = "{"id":1,"name":"John"}"; StringEntity entity = new StringEntity(json); httpPost.setEntity(entity); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); CloseableHttpResponse response = client.execute(httpPost); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); client.close(); }
4 Post with HttpClient Fluent API
使用Request进行post请求:
@Test public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws ClientProtocolException, IOException { HttpResponse response = Request.Post("http://www.example.com").bodyForm( Form.form().add("username", "John").add("password", "pass").build()) .execute().returnResponse(); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); }
5 Post Multipart Request
Post一个Multipart Request:
@Test public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://www.example.com"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("username", "John"); builder.addTextBody("password", "pass"); builder.addBinaryBody("file", new File("test.txt"), ContentType.APPLICATION_OCTET_STREAM, "file.ext"); HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); CloseableHttpResponse response = client.execute(httpPost); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); client.close(); }
6 Upload a File using HttpClient
使用一个Post请求上传一个文件:
@Test public void whenUploadFileUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://www.example.com"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("file", new File("test.txt"), ContentType.APPLICATION_OCTET_STREAM, "file.ext"); HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); CloseableHttpResponse response = client.execute(httpPost); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); client.close(); }
7 Get File Upload Progress
使用HttpClient获取文件上传的进度。扩展HttpEntityWrapper 获取进度。
上传代码:
@Test public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://www.example.com"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("file", new File("test.txt"), ContentType.APPLICATION_OCTET_STREAM, "file.ext"); HttpEntity multipart = builder.build(); ProgressEntityWrapper.ProgressListener pListener = new ProgressEntityWrapper.ProgressListener() { @Override public void progress(float percentage) { assertFalse(Float.compare(percentage, 100) > 0); } }; httpPost.setEntity(new ProgressEntityWrapper(multipart, pListener)); CloseableHttpResponse response = client.execute(httpPost); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); client.close(); }
观察上传进度接口:
public static interface ProgressListener { void progress(float percentage); }
扩展了HttpEntityWrapper的ProgressEntityWrapper:
public class ProgressEntityWrapper extends HttpEntityWrapper { private ProgressListener listener; public ProgressEntityWrapper(HttpEntity entity, ProgressListener listener) { super(entity); this.listener = listener; } @Override public void writeTo(OutputStream outstream) throws IOException { super.writeTo(new CountingOutputStream(outstream, listener, getContentLength())); } }
扩展了FilterOutputStream的CountingOutputStream:
public static class CountingOutputStream extends FilterOutputStream { private ProgressListener listener; private long transferred; private long totalBytes; public CountingOutputStream( OutputStream out, ProgressListener listener, long totalBytes) { super(out); this.listener = listener; transferred = 0; this.totalBytes = totalBytes; } @Override public void write(byte[] b, int off, int len) throws IOException { out.write(b, off, len); transferred += len; listener.progress(getCurrentProgress()); } @Override public void write(int b) throws IOException { out.write(b); transferred++; listener.progress(getCurrentProgress()); } private float getCurrentProgress() { return ((float) transferred / totalBytes) * 100; } }
总结
简单举例说明如何使用Apache HttpClient 4进行各种post请求。做个笔记。
作者:阿凡卢
出处:https://www.cnblogs.com/luxiaoxun/p/6165237.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App