我试图通过HttpPost发送一些数据,但它是空的。如果我的方法和HttpGET部分工作正常。但是当我尝试向Post body添加一些数据并发送时,我没有收到任何错误,而Logcat(另一方面是+ REST Web服务)显示Post数据为空。
public void sendPhoto(View v) {
final String kookojaUrlGet = "http://localhost/getData";
final String kookojaUrlPost = "http://localhost/postData";
new Thread(new Runnable() {
@Override
public void run() {
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse getResponse = httpClient.execute(new HttpGet(kookojaUrlGet));
String returnedStuff = EntityUtils.toString(getResponse.getEntity());
Log.d("debug","http get returned " + returnedStuff);
JSONObject jsonGet = new JSONObject(returnedStuff);
int xxxTime = jsonGet.getInt("timestamp");
String xxxNone = jsonGet.getString("nonce");
String xxxApp = jsonGet.getString("appName");
String xxxCID = jsonGet.getString("csrfToken");
Log.d("debug","json was " + xxxTime + " " + xxxNone + " " + xxxApp + " " + xxxCID);
JSONObject c = new JSONObject();
c.put("_username","xxx@gmail.com");
c.put("_password","123");
c.put("_timestamp", xxxTime);
c.put("_nonce", xxxNone);
c.put("_appName", xxxApp);
c.put("CID", xxxCID);
c.put("body", photoPost);
c.put("long", photoLong);
c.put("lat", photoLat);
StringEntity sendStuff = new StringEntity(c.toString());
HttpPost xxxPost = new HttpPost(kookojaUrlPost);
xxxPost.setHeader("Accept", "application/json");
xxxPost.setHeader("Content-type", "application/json");
xxxPost.setHeader("Accept-Encoding", "gzip");
xxxPost.setEntity(sendStuff);
HttpResponse postResponse = httpClient.execute(xxxPost);
String postText = EntityUtils.toString(postResponse.getEntity());
Log.d("debug", "rest post response was " + postText);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}).start();
}
任何帮助将不胜感激。
答案 0 :(得分:0)
我通过使用“List”而不是JSONObject解决了这个问题。这是代码:
List<NameValuePair> c = new ArrayList<NameValuePair>(2);
c.add(new BasicNameValuePair("_username", "xxx@gmail.com"));
c.add(new BasicNameValuePair("_password", "123"));
c.add(new BasicNameValuePair("_timestamp", xxxTime2));
c.add(new BasicNameValuePair("_nonce", xxxNone));
c.add(new BasicNameValuePair("_appName", xxxApp));
c.add(new BasicNameValuePair("CID", xxxCID));
c.add(new BasicNameValuePair("body", photoPost));
c.add(new BasicNameValuePair("long", "4524524524"));
c.add(new BasicNameValuePair("lat", "242452452"));
xxxPost.setEntity(new UrlEncodedFormEntity(c));