我想从我的Android设备使用远程API,但出于某种原因, UrlEncodedFormEntity 类不会像_
一样转换%5f
,就像远程API一样似乎在期待。因此,使用此代码:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(
new BasicNameValuePair("json",
"{\"params\":{\"player_name\":\"Toto\",
\"password\":\"clearPass\"},
\"class_name\":\"ApiMasterAuthentication\",
\"method_name\":\"login\"}")
);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
ResponseHandler responseHandler = new BasicResponseHandler();
httpClient.execute(httpPost, responseHandler);
使用以下内容向服务器发送帖子请求:
json=%7B%22params%22%3A%7B%22player_name%22%3A%22Toto%22%2C%22password%22%3A%22clearPass%22%7D%2C%22class_name%22%3A%22ApiMasterAuthentication%22%2C%22method_name%22%3A%22login%22%7D
我希望它是这样的(用%5F代替preivous下划线):
json=%7B%22params%22%3A%7B%22player%5Fname%22%3A%22Toto%22%2C%22password%22%3A%22clearPass%22%7D%2C%22class%5Fname%22%3A%22ApiMasterAuthentication%22%2C%22method%5Fname%22%3A%22login%22%7D
我无法控制API,API的官方客户端就像这样。这似乎是URL normalization
的预期行为我错过了什么吗?我首先认为这是一个UTF-8编码问题,但在HTTP.UTF-8
的构造函数中添加UrlEncodedFormEntity
并不能解决问题。
感谢您的帮助。
编辑:最后,问题不是来自这个unescape下划线。即使我试图重现其他客户端的行为逃脱了它,我只需要设置正确的标题:
httpPost.addHeader("Content-Type","application/x-www-form-urlencoded");
请求工作正常。谢谢大家,尤其是singh.jagmohan的帮助(即使问题最终在其他地方)!
答案 0 :(得分:3)
“_”不是网址的保留符号。
设置:Content-Type: application/x-www-form-urlencoded
'
应该解决问题。否则你可以尝试更换它,如果你真的需要这个选项:
String.Replace("_", "%5f");
答案 1 :(得分:1)
您可以尝试以下代码,它适用于我。
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(serviceUrl);
MultipartEntity multipartEntity = new MultipartEntity();
// Also, in place of building JSON string as below, you can build a **JSONObject**
// and then use jsonObject.toString() while building the **StringBody** object
String requestJsonStr = "{\"params\":{\"player_name\":\"Toto\",\"password\":\"clearPass\"},\"class_name\":\"ApiMasterAuthentication\",\"method_name\":\"login\"}";
multipartEntity.addPart("json", new StringBody(requestJsonStr));
httpPost.setEntity(multipartEntity);
HttpResponse response = httpClient.execute(httpPost);
} catch (Exception ex) {
// add specific exception catch block above
// I have used this one just for code snippet
}
PS:代码段需要两个jar文件 apache-mime4j-0.6.jar 和 httpmime-4.0.1.jar 。< / p>
希望这有帮助。