【发布时间】:2011-04-09 11:41:23
【问题描述】:
我一直在开发一个使用 GET 和 POST 请求到 Web 服务的应用程序。 GET 请求没有问题,但 POST 请求让我很生气。我在代码中尝试了 2 种不同的场景。第一个看起来像这样......
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(ws);
JSONObject jsonObject = new JSONObject();
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
jsonObject.put("action", "login");
jsonObject.put("username", "*********");
jsonObject.put("password", "*********");
httppost.setHeader("jsonString", jsonObject.toString());
StringEntity se = new StringEntity( jsonObject.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
textview.setText(getResponse(response.getEntity()));
} catch (ClientProtocolException e) {
textview.setText(e.getLocalizedMessage());
} catch (IOException e) {
textview.setText(e.getLocalizedMessage());
} catch (JSONException e) {
textview.setText(e.getLocalizedMessage());
}
这段代码为我得到了这个结果...
“Bad Request (Invalid Header Name)”
现在这是我的第二段代码...
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(ws);
JSONObject jsonObject = new JSONObject();
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
jsonObject.put("action", "login");
jsonObject.put("username", "******");
jsonObject.put("password", "******");
nameValuePairs.add(new BasicNameValuePair("jsonString", jsonObject.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
textview.setText(getResponse(response.getEntity()));
} catch (ClientProtocolException e) {
textview.setText(e.getLocalizedMessage());
} catch (IOException e) {
textview.setText(e.getLocalizedMessage());
} catch (JSONException e) {
}
这给了我一个完全不同的结果。这是一个长期乱码的 xml 和 SOAP,其中确实提到了 SOAP 异常...
“服务器无法处理请求。--- System.Xml.XmlException:根级别的数据是无效。第 1 行,位置 1。"
现在,任何人都可以阐明我做错了什么。
【问题讨论】:
标签: java android web-services json http-post