工作中遇到的问题:需求是在请求头中添加自定义参数 Authorization 。
尝试使用restTemplate 没有成功,这里使用HttpClient,直接上代码了
package com.cmcc.andedu.util;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpClientTools {
private static Logger log = LoggerFactory.getLogger(HttpClientTools.class);
/**
* @Description post请求,添加hearder
* @param path path绝对路径
* @param body JSON格式字符串
* @return
**/
public String doPost(String path, String token, String body){
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(path);
//添加header参数
httpPost.addHeader("Authorization","Bearer "+token);
httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
//这里需要指定请求参数的编码,否则默认是ISO_8859_1
StringEntity stringEntity = new StringEntity(body,"UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
HttpResponse response = httpclient.execute(httpPost);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity,"UTF-8");
}
}
}catch (Exception e){
log.error("请求异常:"+path);
e.printStackTrace();
}
return result;
}
}
|
不得不说,httpclient 还是很强大的。
欢迎留言指正! |
版权声明:本文为theweather原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。