Android 新手,我需要在我的网络服务调用中使用以下参数。我理解参数实际上是 JSON 对象。
当它应该返回登录用户信息时,下面的代码返回带有“title: Bad request”的 XML。 logcat 的值显示为 --> json: {"Query":"com.androidatc.customviewindrawer.Query@f1eb09f","includeUserMiscInfo":true} 表示我的参数不正确。如何正确传递?
protected void sendJson(final String email, final String pwd) {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost("http://192.168.0.102/SDService_SAFTI/ServiceSD.svc/LoginUser");
Query queryObj = new Query();
queryObj.setLogin("WT");
queryObj.setPassword("3");
json.put("Query", queryObj);
// json.put("email", email);
// json.put("password", pwd);
json.put("includeUserMiscInfo", true);
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
Toast.makeText(getActivity().getApplicationContext(), "Response:" + convertStreamToString(in),Toast.LENGTH_LONG).show();
}
} catch(Exception e) {
e.printStackTrace();
// getActivity().createDialog("Error", "Cannot Estabilish Connection");
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
查询.java
public class Query {
String login;
public void setPassword(String password) {
this.password = password;
}
public void setLogin(String login) {
this.login = login;
}
String password;
public String getPassword() {
return password;
}
public String getLogin() {
return login;
}
}
如有任何建议,我们将不胜感激。非常感谢。
最佳答案
作为您的 Json 类型,您可能必须这样做,
JSONArray array = new JSONArray();
array.put("login=WT&password=3");
json.put("Query", array);
json.put("includeUserMiscInfo", "true");
我想建议你也尝试替换这条线,
json.put("includeUserMiscInfo", true);
与
json.put("includeUserMiscInfo", "true");
关于android - 在 Web 服务中将 JSON 对象作为参数传递 - 返回 "Bad Request"响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35738165/