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"));
// 第二個參數(shù),設置后才會對,內容進行編碼
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);
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,544評論 19 139
  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,265評論 6 342
  • 22年12月更新:個人網(wǎng)站關停,如果仍舊對舊教程有興趣參考 Github 的markdown內容[https://...
    tangyefei閱讀 35,393評論 22 257
  • HTML表單 在HTML中,表單是 ... 之間元素的集合,它們允許訪問者輸入文本、選擇選項、操作對象等等,然后將...
    蘭山小亭閱讀 3,505評論 2 14
  • HTML標簽解釋大全 一、HTML標記 標簽:!DOCTYPE 說明:指定了 HTML 文檔遵循的文檔類型定義(D...
    米塔塔閱讀 3,526評論 1 41

友情鏈接更多精彩內容