在我的下面代码中,我将json字符串发布到服务器。虽然我已经写了postParams.add(new BasicNameValuePair(“json_data”,jsonStr));它给出了参数json_data未传递的错误。
我不确定为什么它会给我错误。
OrderjsonArray.put(order1);
LocationjsonArray.put(location1);
LocationjsonArray.put(location2);
order1.put("locations", LocationjsonArray);
JSONObject ordersObj = new JSONObject();
ordersObj.put("orders", OrderjsonArray);
String jsonStr = ordersObj.toString();
String contentType = "application/json";
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("json_data", jsonStr));
HttpGet httpGet = null;
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
entity.setContentEncoding(HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", contentType);
httpPost.setHeader("Accept", contentType);
} catch (UnsupportedEncodingException e) {
}
HttpResponse httpResponse = httpclient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
答案 0 :(得分:0)
您正在发送json文本作为名称值对的值。但是你的其余代码意味着你必须将它作为multipart formdata发送。显然,服务器也不会查看名称值对。
答案 1 :(得分:0)
使用以下代码
try {
HttpPost httppost1 = null;
HttpClient httpclient1 = new DefaultHttpClient();
if (userchk.equalsIgnoreCase("client")) {
httppost1 = new HttpPost(
ApplicationData.serviceURL
+ "/clientLogin");
} else if (userchk.equalsIgnoreCase("driver")) {
httppost1 = new HttpPost(
ApplicationData.serviceURL
+ "/driverLogin");
}
Log.e("9", "9");
// Add your data
List<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>(
2);
nameValuePairs1.add(new BasicNameValuePair(
"vEmail", email.getText().toString()));
nameValuePairs1.add(new BasicNameValuePair(
"vPassword", password.getText()
.toString()));
httppost1.setEntity(new UrlEncodedFormEntity(
nameValuePairs1));
// Execute HTTP Post Request
HttpResponse response1 = httpclient1
.execute(httppost1);
BufferedReader in1 = new BufferedReader(
new InputStreamReader(response1
.getEntity().getContent()));
StringBuffer sb1 = new StringBuffer("");
String line1 = "";
while ((line1 = in1.readLine()) != null) {
sb1.append(line1);
}
in1.close();
Log.e(userchk + " login original data",
sb1.toString());
return sb1.toString();
} catch (Exception e) {
return "";
}