如何JSON参数发送给在Android的Web服务请求? [英] How to send JSON parameters as web service request in Android?

查看:164
本文介绍了如何JSON参数发送给在Android的Web服务请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  <一href="http://stackoverflow.com/questions/3027066/how-to-send-a-json-object-over-request-with-android">How与Android的发送JSON对象在申请?

由于我是新的Andr​​oid开发,我打了一个问题,JSON的形式将请求发送到Web服务。谷歌搜索,我发现以下code 发送使用参数的请求。这是我们在形式发送参数的Java类:

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 code for sending requests using parameters. Here is the Java class we are sending parameters in the form of:

Main.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();

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

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

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

那么,谁能帮助我?我如何在JSON形式发送参数?

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

推荐答案

你是发布采用图书馆被人放在一起作为围绕Apache的HttpClient的类包装的例子。这不是一个特别好的。但你并不需要使用包装可言,HttpClient的本身是死的简单运用。这里有一个code样品,你可以建立在:

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:

final String uri = "http://www.example.com";
final String body = String.format("{\"login\": {\"Email\": \"%s\", \"Passwd\": \"%s\"}", "me@email.com", "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
}

请注意,你最有可能被使用JSON库序列化POJO和创建请求JSON。

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

这篇关于如何JSON参数发送给在Android的Web服务请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆