Android 未设置HTTPUrlConnection中的HTTP POST数据?
我正在android中创建一个HTTPUrlConnection,并为如下所示的帖子做准备Android 未设置HTTPUrlConnection中的HTTP POST数据?,android,django,http,rest,tastypie,Android,Django,Http,Rest,Tastypie,我正在android中创建一个HTTPUrlConnection,并为如下所示的帖子做准备 urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("content-type", "application/json"); byte [] encoded = Base64.encode((username+":"+password).getBytes("UTF-8"),
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("content-type", "application/json");
byte [] encoded = Base64.encode((username+":"+password).getBytes("UTF-8"), Base64.DEFAULT);
//Basic Authorization
urlConnection.setRequestProperty("Authorization", "Basic "+ new String(encoded, "UTF-8"));
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
//This gets implicitly set when DoOutput is True, but still let it be
urlConnection.setRequestMethod("POST");
//Required for POST not to return 404 when used on with a host:port combination
//http://stackoverflow.com/questions/5379247/filenotfoundexception-while-getting-the-inputstream-object-from-httpurlconnectio
urlConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:17.0) Gecko/20100101 Firefox/17.0");
urlConnection.setRequestProperty("Accept","*/*");
然后准备JSON并将其写入连接的OutputStream
JSONObject jsonObject = new JSONObject();
jsonObject.put("key1", "value1");
jsonObject.put("key2", "value2");
outputStreamWriter = urlConnection.getOutputStream ();
outputStreamWriter.write(jsonObject.toString().getBytes());
finally {
if (outputStreamWriter != null) try { outputStreamWriter.close(); } catch (IOException logOrIgnore) {}
}
当我执行请求时,我的状态为500,因为我的服务器接收到一个无效json的空POST数据
这同样适用于web浏览器和curl。GET在android上使用相同的参数工作。我错过了什么?为POST请求设置参数的方式顺序有问题吗?我能够让它正常工作。下面的代码片段 创建要发送的数据时,请注意所需的转义引号
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("\A\"", "\"/api/v1/a/1/\""));
nameValuePairs.add(new BasicNameValuePair("\"B\"", "\"/api/v1/b/1/\""));
nameValuePairs.add(new BasicNameValuePair("\"C\"", "\"Hello from Android\""));
设置授权标头
String encoded = "Basic " + Base64.encodeToString((username+":"+password).getBytes("UTF-8"), Base64.URL_SAFE|Base64.NO_WRAP);
httppost.setHeader("Authorization",encoded);
将数据串起来,并将其设置为POST请求中的HTTP参数
StringEntity entity = new StringEntity(getQueryJSON(nameValuePairs));
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
readStream(in);
}
将JSON编码为字符串的实用函数
私有字符串getQueryJSON(列表参数)引发UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first){
first = false;
result.append("{");
}else
result.append(",");
result.append(pair.getName());
result.append(":");
result.append(pair.getValue());
}
result.append("}");
return result.toString();
}
您的服务器是否接收其余的请求?(身份验证,用户代理?@NiravRanpara-GET可以工作,POST不能工作,但由于数据问题而失败。我的清单中有INTERNET权限。您是否尝试刷新并记录在关闭或写入过程中可能收到的任何异常?(outputStreamWriter.write应位于try{}catch块中,是否记录异常?)
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first){
first = false;
result.append("{");
}else
result.append(",");
result.append(pair.getName());
result.append(":");
result.append(pair.getValue());
}
result.append("}");
return result.toString();
}