HttpClient Post请求
前言
`HttpClient Post请求
提示:以下是本篇文章正文内容,下面案例可供参考
一、HttpClient Post请求。
工作记录
一、使用步骤
## 2.读入数据
代码如下(示例):
```c
public static String httpPost(String jsonStr, String url, String token) {
String result = null;
HttpPost post = null;
HttpClient httpClient = HttpClients.createDefault();
String remoteUrl = url;
try {
post = new HttpPost(remoteUrl);
// 构造消息头x`
post.setHeader("Content-type", "application/json; charset=utf-8");
if (token != null && !"".equals(token)){
post.setHeader("Authorization", "Basic " + token);
}
// 构建消息实体
StringEntity entity = new StringEntity(jsonStr, Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
// 发送Json格式的数据请求
entity.setContentType("application/json");
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
// 检验返回码
int statusCode = response.getStatusLine().getStatusCode();
log.error("返回的状态码"+statusCode);
if (statusCode == HttpStatus.SC_OK) {
HttpEntity he = response.getEntity();
String respContent = EntityUtils.toString(he, "UTF-8");
return respContent;
} else {
result = "HTTP POST 请求异常错误码[" + statusCode + "]";
return result;
}
} catch (Exception e) {
log.error(e.getMessage());
result = e.getMessage();
return result;
}
}
总结
提示:工作记录http post请求