我需要通过HTTP POST向服务发送一些值。发送的其中一个参数必须包含空格。它是" Key" NVP。但是,只要我添加一个有效的值,该服务就会始终返回一条不成功的消息。
现在这里是捕获,当通过iphone设备对同一服务进行请求时,它们在发送BLANKS时工作正常,我是否在请求中遗漏了允许通过NameVauePair发送空值的东西?
这是我的NaveValuePair'
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("id","1"));
nameValuePairs.add(new BasicNameValuePair("uId",android_id));
nameValuePairs.add(new BasicNameValuePair("Key", " ")); // This value must be BLANKS
nameValuePairs.add(new BasicNameValuePair("Rate","0"));
nameValuePairs.add(new BasicNameValuePair("Notes", notes));
这是我的POST请求
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(context.getResources()
.getString(R.string.url_event_rating));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response
.getEntity());
} catch (ClientProtocolException e) {
Log.d("ClientProtocolException", e.getMessage());
} catch (IOException e) {
Log.d("IOException", e.getMessage());
}
答案 0 :(得分:1)
尝试添加SP
而不是文字空格字符。这是BasicNameValuePair为您提供的语法:http://developer.android.com/reference/org/apache/http/message/BasicNameValuePair.html(指定类的一般概述)和http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2(指定接受的标记)。
基本上,根据我对此主题的了解,您希望插入SP
而不是" "
。
修改:根据上面的第二个链接:SP = <US-ASCII SP, space (32)>
。基本上,要么放置一个值为32(十进制)或0x20(十六进制)的字符。或者,将UrlEncodedFormEntity(nameValuePairs, "utf-8")
中的编码更改为"US-ASCII"
。
答案 1 :(得分:0)
当我们发送POST请求时,要设置HTTP标头中的字段,例如值为Content-Type
的{{1}}字段,这是默认类型。我们应该在发送之前编码请求正文的"application/x-www-form-urlencoded"
字段。 URLEncoder.encode(String s, String charsetName
)函数对给定value
的字符串进行编码,即charsetName
。默认情况下使用的编码基于一般URI percent encoding规则的早期版本。
一个编码示例:像'utf-8'
这样的字符串将被编码为:
My Name is "Marshal"
。
因此,最安全的方法是在使用此函数进行编码后设置My%20Name%20is%20%22Marshal%22
对。那就是:
(name, value)
答案 2 :(得分:-1)
好的,可能还有其他方法可以让它工作,但以下代码对我有用。
我使用以下方法让它工作。
String blanks = " ";
nameValuePairs.add(new BasicNameValuePair("Key", blanks.replaceAll(" ", "%20")));
希望这可以帮助遇到同样问题的人。