我们在实际开发中常常会遇到这种问题:在一个项目中需要访问另一个项目的接口获取需要的内容。因此我们就涉及到了HttpClient请求的问题,主要包括两种方式:HttpPost和HttpGet两种。用于多服务器之间互相访问。
一、HttpGet请求
public String doHttpGet() {
// 需要访问的接口路径
String url = "http://124.114.27.135:3110/checkAuto/getLevel?levelId=13";
// 配置请求信息(请求时间)
RequestConfig rc = RequestConfig.custom().setSocketTimeout(5000)
.setConnectTimeout(5000).build();
// 获取使用DefaultHttpClient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 返回结果
String result = null;
try {
if (url != null) {
// 创建HttpGet对象,将URL通过构造方法传入HttpGet对象
HttpGet httpget = new HttpGet(url);
// 将配置好请求信息附加到http请求中
httpget.setConfig(rc);
// 执行DefaultHttpClient对象的execute方法发送GET请求,通过CloseableHttpResponse接口的实例,可以获取服务器返回的信息
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// 得到返回对象
HttpEntity entity = response.getEntity();
if (entity != null) {
// 获取返回结果
result = EntityUtils.toString(entity);
}
} finally {
// 关闭到客户端的连接
response.close();
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭http请求
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
StringEntity格式编码问题
//第一种方式:后端无法解码,因为默认的接收格式是ISO_5598_1
StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(params));
//第二种方式:请求成功,设置的接收格式是UTF-8
StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(params), “UTF-8”);
public StringEntity(String string) throws UnsupportedEncodingException {
this(string, ContentType.DEFAULT_TEXT);
}
public StringEntity(String string, ContentType contentType) throws UnsupportedCharsetException {
Args.notNull(string, "Source string");
Charset charset = contentType != null ? contentType.getCharset() : null;
if (charset == null) {
charset = HTTP.DEF_CONTENT_CHARSET;
}
this.content = string.getBytes(charset);
if (contentType != null) {
this.setContentType(contentType.toString());
}
}
当不传入ContentType时,会使用默认值,而该处的默认编码格式是:ISO_5598_1。所以后端才会提示异常。
总结:使用httpclient时,尽量使用第二种方式来初始化StringEntity,避免因为编码格式导致异常。
原文链接:https://blog.csdn.net/wangjin890620/article/details/87864337