Json发布特定格式数据并在android中获得响应

时间:2015-01-29 12:53:32

标签: java android json

我需要以这种格式通过json url发布数据

{
"Authentication":   
{
  "Username": "testUser@123",
  "Password": "testPassword@123"
},
"RequestType": 4
}

并获取android .how中特定请求的响应,如果你有意,请帮助我

1 个答案:

答案 0 :(得分:1)

尝试使用此代码,使用post方法将json发送到服务器。

try {
            HttpClient httpClient = new DefaultHttpClient();
            JSONObject object = new JSONObject();
            object.put("Username", "testUser@123");
            object.put("Password", "testPassword@123");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Authentication", object);
            jsonObject.put("RequestType", 4);
            HttpPost postMethod = new HttpPost("your_url");
            postMethod.setEntity(new StringEntity(jsonObject.toString()));
            postMethod.setHeader("Accept", "application/json");
            postMethod.setHeader("Content-type", "application/json");
            HttpResponse response = httpClient.execute(postMethod);
            HttpEntity entity = response.getEntity();
            String response_value = EntityUtils.toString(entity).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }