把原来的 :httpPost.setEntity( new StringEntity(字符串.toString()));改为以下几行就完美解决:
StringEntity entity1 = new StringEntity(body.toString(),"utf-8");//解决中文乱码问题
entity1.setContentEncoding("UTF-8"); //解决中文乱码问题
entity1.setContentType("application/json"); //解决中文乱码问题
httpPost.setEntity(entity1);
logger.info("请求地址:"+url);
上代码。
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.css.eshop.model.Respones;
import com.css.eshop.model.TokenVo;
import com.google.gson.Gson;
public class HttpClientNoValidation {
protected static Log logger = LogFactory.getLog(HttpClientUtil.class);
/**
* 模拟请求
*
* @param url 资源地址
* @param map 参数列表
* @param encoding 编码
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
* @throws ClientProtocolException
*/
public static Respones sendJsonPost(String url, String body,String encoding) throws KeyManagementException, NoSuchAlgorithmException, ClientProtocolException, IOException {
//采用绕过验证的方式处理https请求
SSLContext sslcontext = createIgnoreVerifySSL();
// 设置协议http和https对应的处理socket链接工厂的对象
Registry socketFactoryRegistry = RegistryBuilder.create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager);
//创建自定义的httpclient对象
CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
// CloseableHttpClient client = HttpClients.createDefault();
//创建post方式请求对象
HttpPost httpPost = new HttpPost(url);
//装填参数
/*List nvps = new ArrayList();
if(map!=null){
for (Entry entry : map.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
//设置参数到请求对象中
httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
logger.info("请求参数:"+nvps.toString());
*/
StringEntity entity1 = new StringEntity(body.toString(),"utf-8");//解决中文乱码问题
entity1.setContentEncoding("UTF-8"); //解决中文乱码问题
entity1.setContentType("application/json"); //解决中文乱码问题
httpPost.setEntity(entity1);
logger.info("请求地址:"+url);
//设置header信息
//指定报文头【Content-type】、【User-Agent】
//httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
httpPost.setHeader("Content-type", "application/json;charset=UTF-8");
Respones responseVo = new Respones();
String strResult = "";
CloseableHttpResponse response=null;
try {
//执行请求操作,并拿到结果(同步阻塞)
response = client.execute(httpPost);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
strResult = EntityUtils.toString(entity, encoding);
}
logger.info("传入参数:"+body);
int iGetResultCode = response.getStatusLine().getStatusCode();
responseVo.setResponeCde(iGetResultCode);
responseVo.setResult(strResult);
//EntityUtils.consume(entity);
} catch (Exception ex) {
responseVo.setResponeCde(500);
responseVo.setResult("error");
logger.error("executeGetMethod", ex);
} finally {
try {
if(response !=null){
response.close();
}
} catch (Exception e) {
logger.error("executeGetMethod", e);
}
}
return responseVo;
}
/**
* 绕过验证
*
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sc = SSLContext.getInstance("SSLv3");
// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sc.init(null, new TrustManager[] { trustManager }, null);
return sc;
}
}
通过传参,body里面可以是json数据,然后调用对方的接口。
再看看以下的参考代码:
public static String httpPostWithJSON(String url) throws Exception {
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();
String respContent = null;
// json方式
JSONObject jsonParam = new JSONObject();
jsonParam.put("name", "admin");
jsonParam.put("pass", "123456");
StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
System.out.println();
// 表单方式
// List pairList = new ArrayList();
// pairList.add(new BasicNameValuePair("name", "admin"));
// pairList.add(new BasicNameValuePair("pass", "123456"));
// httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
HttpResponse resp = client.execute(httpPost);
if(resp.getStatusLine().getStatusCode() == 200) {
HttpEntity he = resp.getEntity();
respContent = EntityUtils.toString(he,"UTF-8");
}
return respContent;
}
public static void main(String[] args) throws Exception {
String result = httpPostWithJSON("http://localhost:8080/hcTest2/Hc");
System.out.println(result);
}
post方式 就要考虑提交的表单内容怎么传输了。本文name和pass就是表单的值了。
封装表单属性可以用json也可以用传统的表单,如果是传统表单的话 要注意,也就是在上边代码注释那部分。用这种方式的话在servlet里也就是数据处理层可以通过request.getParameter(”string“)直接获取到属性值。就是相比json这种要简单一点,不过在实际开发中一般都是用json做数据传输的。用json的话有两种选择一个是阿里巴巴的fastjson还有一个就是谷歌的gson。fastjson相比效率比较高,gson适合解析有规律的json数据。博主这里用的是fastjson。还有用json的话在数据处理层要用流来读取表单属性,这就是相比传统表单多的一点内容。代码下边已经有了。
public class HcServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
String acceptjson = "";
User user = new User();
BufferedReader br = new BufferedReader(new InputStreamReader(
(ServletInputStream) request.getInputStream(), "utf-8"));
StringBuffer sb = new StringBuffer("");
String temp;
while ((temp = br.readLine()) != null) {
sb.append(temp);
}
br.close();
acceptjson = sb.toString();
if (acceptjson != "") {
JSONObject jo = JSONObject.parseObject(acceptjson);
user.setUsername(jo.getString("name"));
user.setPassword(jo.getString("pass"));
}
request.setAttribute("user", user);
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
}
参考文章:https://www.cnblogs.com/Vdiao/p/5339487.html