如何获得JSON响应 [英] How to get Json response

查看:173
本文介绍了如何获得JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

林很新的Andr​​oid游戏..我想从RESTful Web服务的响应。 web服务工作正常。但是,如何在Android获得响应..如果我运行请稍候进度只来申请...请任何人的帮助。

下面我code

\r
\r

公共无效invokeWS(RequestParams PARAMS){\r
            //显示进度对话框\r
            prgDialog.show();\r
            //使用AsyncHttpClient对象进行RESTful Web服务调用\r
            AsyncHttpClient客户端=新AsyncHttpClient();\r
            client.get(http://192.168.2.2:9999/useraccount/login/dologin,则params,新JsonHtt presponseHandler(){\r
                //当REST返回的响应有HTTP响应code'200'\r
                @覆盖\r
                公共无效的onSuccess(INT状态code,头[]头,弦乐响应){\r
                    //隐藏进度对话框\r
                    prgDialog.hide();\r
                    尝试{\r
                        // JSON对象\r
                        JSONObject的OBJ =新的JSONObject(响应);\r
                        //当JSON响应有状态的boolean值分配与真实\r
                        如果(obj.getBoolean(身份)){\r
                            Toast.makeText(getActivity()getApplicationContext(),您已成功登录了!,Toast.LENGTH_LONG).show();\r
                            //导航至主屏幕\r
                            // navigatetoHomeActivity();\r
                        }\r
                        //否则显示错误信息\r
                        其他{\r
                            errorMsg.setText(obj.getString(ERROR_MSG));\r
                            Toast.makeText(getActivity()getApplicationContext(),obj.getString(ERROR_MSG),Toast.LENGTH_LONG。).show();\r
                        }\r
                    }赶上(JSONException E){\r
                        // TODO自动生成catch块\r
                        Toast.makeText(getActivity()getApplicationContext(),出现错误[服务器的JSON响应可能无效]!,Toast.LENGTH_LONG).show();\r
                        e.printStackTrace();\r
\r
                    }\r
                }\r
\r
                //当REST返回的响应有HTTP响应$ C $不是'200'其他C\r
                @覆盖\r
                公共无效onFailure处(INT状态code,头[]标题,内容的字符串,可抛出错误){\r
                    //隐藏进度对话框\r
                    prgDialog.hide();\r
                    //当HTTP响应code是'404'\r
                    如果(状态code == 404){\r
                        Toast.makeText(getActivity()getApplicationContext(),请求的资源未找到,Toast.LENGTH_LONG).show();\r
                    }\r
                    //当HTTP响应code是'500'\r
                    否则,如果(状态code == 500){\r
                        Toast.makeText(getActivity()getApplicationContext(),出事了服务器端,Toast.LENGTH_LONG).show();\r
                    }\r
                    //当HTTP响应code比404其他,500\r
                    其他{\r
                        Toast.makeText(getActivity()getApplicationContext(),意外的错误occcured [最常见的错误:设备可能没有连接互联网或远程服务器是跑不起来]!,Toast.LENGTH_LONG).show();\r
                    }\r
\r
                }\r
            });\r
        }

\r

\r
\r

在上面code,头[]自动的onSuccess方法重拳出击。如何解决它。请人帮助我!


解决方案

首先要确保你有你的清单中的权限:

 <使用许可权的android:NAME =android.permission.INTERNET对/>

现在第二个是,我建议你使用排球获取请求。它易于使用,如果你使用Android工作室它更容易插件库。只是这行添加到您app.gradle的依赖,你是好去。

 编译com.mcxiaoke.volley:库:1.0.17

有关镜像库的更多信息请点击这里

现在实现:

 公共无效sendRequest将(查看视图){
        progressDialog.setMessage(请稍候);
        progressDialog.show();        字符串URL =YOUR_URL;        //请求提供的URL字符串响应。
        StringRequest stringRequest =新StringRequest(Request.Method.GET,网址,
                新Response.Listener<串GT;(){
                    @覆盖
                    公共无效onResponse(字符串响应){
                        Log.e(信息,响应是:+响应);
                        progressDialog.dismiss();                    }
                },新Response.ErrorListener(){
            @覆盖
            公共无效onErrorResponse(VolleyError错误){
                Log.e(信息,错误);
                error.printStackTrace();
                progressDialog.dismiss();
            }
        });        stringRequest.setTag(YOUR_TAG);
        //添加请求到请求队列。
        queue.add(stringRequest);
    }

和取消您的请求。

 公共无效CancelRequest(查看视图){
        queue.cancelAll(YOUR_TAG);
        Log.e(信息,请求取消);
    }

有关要显示的情况下,你需要改变的片段更容易处理只需添加这对暂停或停止上。古德勒克!

Im very new for android.. I want to get response from restful webservice. Webservice works fine. But, how get response from android.. If i run the application please wait progress only came... Please anyone help

Here my code

 public void invokeWS(RequestParams params){
            // Show Progress Dialog
            prgDialog.show();
            // Make RESTful webservice call using AsyncHttpClient object
            AsyncHttpClient client = new AsyncHttpClient();
            client.get("http://192.168.2.2:9999/useraccount/login/dologin", params, new JsonHttpResponseHandler() {
                // When the response returned by REST has Http response code '200'
                @Override
                public void onSuccess(int statusCode, Header[] headers, String response) {
                    // Hide Progress Dialog
                    prgDialog.hide();
                    try {
                        // JSON Object
                        JSONObject obj = new JSONObject(response);
                        // When the JSON response has status boolean value assigned with true
                        if (obj.getBoolean("status")) {
                            Toast.makeText(getActivity().getApplicationContext(), "You are successfully logged in!", Toast.LENGTH_LONG).show();
                            // Navigate to Home screen
                            //navigatetoHomeActivity();
                        }
                        // Else display error message
                        else {
                            errorMsg.setText(obj.getString("error_msg"));
                            Toast.makeText(getActivity().getApplicationContext(), obj.getString("error_msg"), Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        Toast.makeText(getActivity().getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }
                }

                // When the response returned by REST has Http response code other than '200'
                @Override
                public void onFailure(int statusCode, Header[] headers, String content, Throwable error) {
                    // Hide Progress Dialog
                    prgDialog.hide();
                    // When Http response code is '404'
                    if (statusCode == 404) {
                        Toast.makeText(getActivity().getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
                    }
                    // When Http response code is '500'
                    else if (statusCode == 500) {
                        Toast.makeText(getActivity().getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
                    }
                    // When Http response code other than 404, 500
                    else {
                        Toast.makeText(getActivity().getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
                    }

                }
            });
        }

In above code, Header[] automatically strike out in onSuccess method. How to fix it. Please anyone help me!!

解决方案

first of all make sure you have the permission on your manifest:

<uses-permission android:name="android.permission.INTERNET" />

Now second is that I suggest you to use Volley for request. It's easy to use and in case you're using Android studio it's much easier to plugin the library. Just add this line to your app.gradle dependencies and you're good to go.

compile 'com.mcxiaoke.volley:library:1.0.17'

For more information about the mirror library click here

now for sample implementation:

public void SendRequest(View view){
        progressDialog.setMessage("Please wait");
        progressDialog.show();

        String url ="YOUR_URL";

        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.e("Message", "Response is: " + response);
                        progressDialog.dismiss();

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("Message", "Error");
                error.printStackTrace();
                progressDialog.dismiss();
            }
        });

        stringRequest.setTag("YOUR_TAG");
        // Add the request to the RequestQueue.
        queue.add(stringRequest);
    }

and to cancel your request

public void CancelRequest(View view){
        queue.cancelAll("YOUR_TAG");
        Log.e("Message", "Request cancelled");
    }

For easier handling in case you need to change fragments to be displayed just add this on pause or on stop. Goodluck!

这篇关于如何获得JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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