java 如何在 Android 中将 JSON 参数作为 Web 服务请求发送?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13548687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:11:08  来源:igfitidea点击:

How to send JSON parameters as web service request in Android?

javaandroidjsonweb-serviceshttpclient

提问by Perception

Possible Duplicate:
How to send a JSON object over Request with Android?

可能的重复:
如何使用 Android 通过 Request 发送 JSON 对象?

As I am new to Android development, I struck up with a problem sending requests to a web service in the form of JSON. Googling, I found the following codefor sending requests using parameters. Here is the Java class we are sending parameters in the form of:

由于我是 Android 开发的新手,我遇到了以 JSON 形式向 Web 服务发送请求的问题。谷歌搜索,我找到了以下使用参数发送请求的代码。这是我们以以下形式发送参数的 Java 类:

Main.java

主程序

RestClient client = new RestClient(LOGIN_URL);
client.AddParam("Email", _username);
client.AddParam("Passwd", _password);

try {
  client.Execute(RequestMethod.POST);
} catch (Exception e) {
  e.printStackTrace();
}
String response = client.getResponse();

But here I want to send parameters in the form of JSON, like for example I want to send parameters in this form:

但在这里我想以 JSON 的形式发送参数,例如我想以这种形式发送参数:

{
  "login":{
    "Email":_username,
    "Passwd":_password,
  }
}

So, can anyone help me? How can I send parameters in the form of JSON?

那么,有人可以帮助我吗?如何以JSON的形式发送参数?

回答by Perception

The example you are posting uses a 'library' put together by someone as a wrapper around Apache's HttpClient class. It's not a particularly good one. But you don't need to use that wrapper at all, the HttpClient itself is dead simple to utilize. Here's a code sample you can build on:

您发布的示例使用由某人组合在一起的“库”作为 Apache 的 HttpClient 类的包装器。这不是一个特别好的。但是您根本不需要使用该包装器,HttpClient 本身使用起来非常简单。这是您可以构建的代码示例:

final String uri = "http://www.example.com";
final String body = String.format("{\"login\": {\"Email\": \"%s\", \"Passwd\": \"%s\"}", "[email protected]", "password");

final HttpClient client = new DefaultHttpClient();
final HttpPost postMethod = new HttpPost(uri);
postMethod.setEntity(new StringEntity(body, "utf-8"));

try {
    final HttpResponse response = client.execute(postMethod);
    final String responseData = EntityUtils.toString(response.getEntity(), "utf-8");
} catch(final Exception e) {
    // handle exception here
}

Note that you would most likely be using a JSON library to serialize a POJO and create the request JSON.

请注意,您很可能会使用 JSON 库来序列化 POJO 并创建请求 JSON。