如何调用JSON Web服务?

时间:2014-09-24 11:28:11

标签: android json web-services

我正在尝试调用此Web服务,但它的响应为空

<script type="text/javascript">
    jQuery(document).ready(function(){
        var user = {nick :"rajesh", password:"123456", device_id:"123456677"};
        jQuery.ajax({
            type: "post",
            data :JSON.stringify(user),
            url: "http://localhost:81/sazpin/user/users/index.json",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                console.log(data);
            }
        });
    });
</script>

我的httppost客户端

HttpClient httpClient = new DefaultHttpClient();

// post header
HttpPost httpPost = new HttpPost(url);                  
httpPost.setEntity(se);        
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");

请有人帮助我如何拨打此网络服务并获得回复?

2 个答案:

答案 0 :(得分:1)

试试这段代码。首先创建AsyncTask。

public class ResquestJSON extends AsyncTask<String, Void, String>{
JSONObject jsonObject = new JSONObject();
String response;

protected String doInBackground(String... params){
    HttpPost httpPost = new HttpPost("http://192.168.10.101:8090/download");//your webservice url here
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext httpContext = new BasicHttpContext();
    try {
        jsonObject.put("firstParam", params[0]);
        jsonObject.put("secondParam", params[1]);

        StringEntity se = new StringEntity(jsonObject.toString());
        httpPost.addHeader("Content_Type", "application/json");
        httpPost.setEntity(se);
        HttpResponse httpResponse = httpClient.execute(httpPost, httpContext);

        HttpEntity entity = httpResponse.getEntity();

        if (entity!=null){
            response = EntityUtils.toString(entity);
            entity.consumeContent();
            httpClient.getConnectionManager().shutdown();
        }
    } catch (JSONException|IOException|IllegalArgumentException e) {
        return UtilityConstants.ERROR;
    }
    return response;
}

现在从您的活动中调用此AsyncTask方法。

String response = new ResquestJSON().execute(firstParam, secondParam).get();
JSONObject obj = new JSONObject(response);
String nick = obj.getString("nick");
String password = obj.getString("password");
String deviceId = obj.getString("deviceId");

希望它对你有所帮助。

答案 1 :(得分:0)

URL url = new URL("http://www.example.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
    urlConnection.setDoOutput(true);
    urlConnection.setChunkedStreamingMode(0);

    OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
    writeStream(out);

    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    readStream(in);
} finally {
    urlConnection.disconnect();
}

实现方法writeStream以将内容写为POST数据,并readStream从服务器读取响应数据

相关问题