HttpClient4提交表单(包含文件)
File image = new File("test.jpeg");
HttpClient httpClient = HttpClients.createDefault();
String uri = "http://op.juhe.cn/vercode/index";
HttpPost post = new HttpPost(uri);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("image", image, ContentType.create("image/jpeg"), image.getName());
builder.addTextBody("codeType", "1004");
HttpEntity entity = builder.build();post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
String res = EntityUtils.toString(response.getEntity());
System.out.println(res);
HttpPost 设置编码
HttpPost post=new HttpPost(url);
StringEntity content=new StringEntity(data, Charset.forName("utf-8"));
// 第二个参数,设置后才会对,内容进行编码
content.setContentType("application/json; charset=UTF-8");
content.setContentEncoding("utf-8");post.setEntity(content);
HttpClient3提交表单(包含文件)
File image = new File("test.jpeg");
HttpClient httpClient = new HttpClient();
PostMethod post = new PostMethod(uri);
Part[] parts = {new StringPart("key", accessKey),
new StringPart("codeType", codeType),
new FilePart("image", codeImage, "image/jpg", "UTF-8")};
post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
int status = httpClient.executeMethod(post);
设置代理访问
HttpClient httpClient = HttpClients.createDefault();
HttpHost target = new HttpHost("http://www.baidu.com", 80);
HttpHost proxy = new HttpHost(ip, port);
RequestConfig config = RequestConfig.custom().setProxy(proxy).setConnectTimeout(30000).setSocketTimeout(30000) .setMaxRedirects(1000).build();
HttpGet get = new HttpGet("http://www.baidu.com");
get.setConfig(config);
HttpResponse response = httpClient.execute(target, get);