java httpClient 编码问题

在跟第三方做接口对接的时候,发现,我加密请求过去的数据,对方总是解密失败。

下面是我使用的请求封装:

public static String sendHttpPost(String httpUrl, String params) {
	// 创建HttpPost
	HttpPost httpPost = new HttpPost(httpUrl);
	
	try {
		// 设置参数
		if (params != null && params.trim().length() > 0) {
			StringEntity stringEntity = new StringEntity(params, "UTF-8");  
			stringEntity.setContentType(CONTENT_TYPE_FORM_URL);
			
			httpPost.setEntity(stringEntity);
		}
		
	} catch (Exception e) {
		e.printStackTrace();
	}
	
	return sendHttpPost(httpPost);
}

以上的请求方法,在请求不加密的数据时都是正常的,但是一旦加密就会导致对方解密失败。

而另一种请求封装却可以:

public static String sendHttpPostByFormEntity(String httpUrl, Map<String, String> paraMap) {
	// 创建HttpPost
	HttpPost httpPost = new HttpPost(httpUrl);
	
	try {
		// 设置参数
		List<NameValuePair> paramList = new ArrayList<NameValuePair>();
		
		for (Map.Entry<String, String> entry : paraMap.entrySet()) {
			paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		
		httpPost.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
		
	} catch (Exception e) {
		e.printStackTrace();
	}
	
	return sendHttpPost(httpPost);
}

很奇怪,明明两种方式,服务器端接收到的请求格式应该都是一样的。

 

于是,经过排查发现,因为使用的StringEntity的时候,contentType使用的是application/x-www-form-urlencoded编码类型,而UrlEncodedFormEntity使用的是类似URLEncoder的编码方式,而URLEncoder的实现是将字符串转换为application/x-www-form-urlencoded MIME格式,所以导致了最终编码上的差异。

最终,如果还是需要使用第一种StringEntity的方式,那么将params进行URL编码即可。

猜你喜欢

转载自z724130632.iteye.com/blog/2388224