HttpClient的一些操作

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);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,188评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,172评论 6 342
  • 22年12月更新:个人网站关停,如果仍旧对旧教程有兴趣参考 Github 的markdown内容[https://...
    tangyefei阅读 35,314评论 22 257
  • HTML表单 在HTML中,表单是 ... 之间元素的集合,它们允许访问者输入文本、选择选项、操作对象等等,然后将...
    兰山小亭阅读 8,711评论 2 14
  • HTML标签解释大全 一、HTML标记 标签:!DOCTYPE 说明:指定了 HTML 文档遵循的文档类型定义(D...
    米塔塔阅读 8,731评论 1 41

友情链接更多精彩内容