基本使用百度一大堆,再次不多赘述
Commons的HttpClient项目现在是生命的尽头,不再被开发,已被
Apache HttpComponents项目HttpClient和HttpCore模组取代,提供更好的性能和更大的灵活性。
1 授权认证(authorization)
1.1 Basic Auth 用户名/密码
String auth = DatatypeConverter.printBase64Binary((username + ":" + password).getBytes());
//添加到header中
httpGet.setHeader("Authorization", "Basic " + auth);
1.2 Bearer Token 令牌
//添加到header中
httpGet.setHeader("Authorization", "Bearer " + token);
2 提交形式
2.1 使用json格式提交 相当于postman的 body->raw->json
// post方法中,加入json数据 body-raw-json json是符合json格式的
StringEntity se = new StringEntity(json, UTF_8);
httpPost.setEntity(se);
2.2 上传文件
2.2.1 非form-data提交文件 相当于postman body->raw->binay
//使用文件流的形式上传文件
FileEntity fileEntity = new FileEntity(file);
httpPost.setEntity(fileEntity);
3 综述
上边都是使用multipartEntityBuilder这个类创建参数提交,而在httpclient4.2.5版本没有此类,下面是上传方法
//
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://localhost:20080/shebaoka/uploadSheBaoKaPhoto");
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
Charset.forName("UTF-8"));
multipartEntity.addPart("file", new FileBody(new File("111111111")));
multipartEntity.addPart("name", new StringBody("sss"));
httpPost.setEntity(multipartEntity);
HttpResponse response = null;
try {
response = client.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
4 小问题
4.1 中文编码问题
HttpEntity build = MultipartEntityBuilder.create()
//设置模式为兼容模式,并设置字符集为utf-8
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.setCharset(Charset.forName("utf-8"))
.build();