android - 如何调用 JSON 网络服务?

标签 android json web-services

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

<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");

请有人帮助我如何调用此网络服务并获得响应?

最佳答案

试试这段代码。首先创建您的 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;
}

现在像这样从您的 Activity 中调用此 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");

希望对你有帮助。

关于android - 如何调用 JSON 网络服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26015752/

相关文章:

javascript - 如何检查一个 json 对象数组中的 id 是否存在于另一个嵌套的 json 对象数组中?

java - 未找到 [SaajSoapMessage 的端点映射,SOAP WS 执行期间出现异常

android - 使用 TextWatcher 在 EditText 中设置最大字数限制

android - PreferenceFragment 中的 RunTimeException

android - 在异步线程中启动对话框时出现 BadTokenException

ios - 有没有办法从这个晦涩的对象中获取属性并将其转换为 JSON?

ios - 如何测试 Json 响应是否包含错误或正确的 json

web-services - 无法在 Tomcat Web 服务器(本地)上运行我的 Spring MVC 项目

java - Websphere 中具有自定义 ssl 套接字工厂的 JAX-WS 客户端

java - android从文件中读取