Java 使用名称-值对向服务器发送Json POST
我正在通过url向服务器发送Json Post请求: 请求结构:Java 使用名称-值对向服务器发送Json POST,java,android,json,androidhttpclient,Java,Android,Json,Androidhttpclient,我正在通过url向服务器发送Json Post请求: 请求结构: {"requestdata":{"password":"abc","devicetype":"phone","username":"amrit@pqr.com","locale":"in"},"requestcode":10} // Building post parameters // key and value pair List<NameValuePair> nameValuePair
{"requestdata":{"password":"abc","devicetype":"phone","username":"amrit@pqr.com","locale":"in"},"requestcode":10}
// Building post parameters
// key and value pair
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("requestcode", "10"));
nameValuePair.add(new BasicNameValuePair("devicetype", "phone"));
nameValuePair.add(new BasicNameValuePair("locale", "in"));
nameValuePair.add(new BasicNameValuePair("username", "amrit@pqr.com"));
nameValuePair.add(new BasicNameValuePair("password", "abc"));
RestPost post = new RestPost(loginUrl, nameValuePair);
String Response = post.postData();
Log.i("Response:", Response);
代码快照:
main活动:
{"requestdata":{"password":"abc","devicetype":"phone","username":"amrit@pqr.com","locale":"in"},"requestcode":10}
// Building post parameters
// key and value pair
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("requestcode", "10"));
nameValuePair.add(new BasicNameValuePair("devicetype", "phone"));
nameValuePair.add(new BasicNameValuePair("locale", "in"));
nameValuePair.add(new BasicNameValuePair("username", "amrit@pqr.com"));
nameValuePair.add(new BasicNameValuePair("password", "abc"));
RestPost post = new RestPost(loginUrl, nameValuePair);
String Response = post.postData();
Log.i("Response:", Response);
您当前正在以的形式发送JSON
{
"requestcode": "10",
"devicetype": "phone",
"locale": "in",
"username": "amrit@pqr.com",
"password": "abc"
}
这不是服务器要求的表单。尝试创建要发送的JSON字符串。然后使用:
httppost.setEntity(new StringEntity(jsonString, "UTF8"));
httppost.setHeader("Content-type", "application/json");
将字符串发送到服务器。我正在使用AndroidHttpClient发布请求
AndroidHttpClient httpClient = AndroidHttpClient.newInstance("User Agent");
URL urlObj = new URL(url);
HttpHost host = new HttpHost(urlObj.getHost(), urlObj.getPort(), urlObj.getProtocol());
AuthScope scope = new AuthScope(urlObj.getHost(), urlObj.getPort());
HttpContext credContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost (url);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairsArrayList));
// Execute post request and get http response
HttpResponse httpResponse = httpClient.execute(host, httpPost, credContext);
httpClient.close();
这对我来说非常有效。你能发布完整的错误吗?你是否尝试将json对象发布到服务器,因为你现在编写它的方式会发送post值
AndroidHttpClient http = AndroidHttpClient.new Instance("hai");