java httpClient encoding problem

When I interfaced with a third party, I found that the data I encrypted and requested in the past always failed to decrypt.

Here is the request wrapper I use:

public static String sendHttpPost(String httpUrl, String params) {
	// create HttpPost
	HttpPost httpPost = new HttpPost(httpUrl);
	
	try {
		// Setting parameters
		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);
}

The above request methods are normal when requesting unencrypted data, but once encrypted, the other party will fail to decrypt.

And another request encapsulation can:

public static String sendHttpPostByFormEntity(String httpUrl, Map<String, String> paraMap) {
	// create HttpPost
	HttpPost httpPost = new HttpPost(httpUrl);
	
	try {
		// Setting parameters
		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);
}

It is very strange that the request format received by the server should be the same in both ways.

 

Therefore, after investigation, it was found that when StringEntity was used, contentType used the application/x-www-form-urlencoded encoding type, while UrlEncodedFormEntity used an encoding method similar to URLEncoder, and the implementation of URLEncoder was to convert the string into application/x-www-form-urlencoded MIME format, so it caused the difference in final encoding.

Finally, if you still need to use the first StringEntity method, then URL-encode the params.

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327056966&siteId=291194637
Recommended