代码案例:package com.what21.http.client4_5;
import java.io.File;
import java.io.FileInputStream;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class What21ClientChunkEncodedPost {
public static void main(String[] args) throws Exception {
// 创建HTTPClient
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// POST请求
HttpPost httppost = new HttpPost("http://www.what21.com/");
// POST内容
File file = new File("d://file");
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1, ContentType.APPLICATION_OCTET_STREAM);
reqEntity.setChunked(true);
// FileEntity entity = new FileEntity(file, "binary/octet-stream");
httppost.setEntity(reqEntity);
System.out.println("执行请求: " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println("返回响应: " + response.getStatusLine());
System.out.println("响应内容:" + EntityUtils.toString(response.getEntity()));
System.out.println("----------------------------------------");
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}