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

可能重复:
如何使用Android在Request上发送JSON对象?

由于我是Android开发的新手,我遇到了以JSON的forms向Web服务发送请求的问题。 谷歌搜索,我发现以下代码使用参数发送请求。 这是我们以下列forms发送参数的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的forms发送参数,例如我想以这种forms发送参数:

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

那么,任何人都可以帮助我吗? 如何以JSON的forms发送参数?

您发布的示例使用由某人组成的“库”作为Apache的HttpClient类的包装器。 这不是一个特别好的。 但是你根本不需要使用那个包装器,HttpClient本身很容易使用。 这是您可以构建的代码示例:

 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。