如何获得Json的回复

时间:2015-07-14 06:32:23

标签: java android

我是非常新的Android ..我想得到来自restful webservice的回复。 Webservice工作正常。但是,如何从Android获得响应..如果我运行应用程序请等待进展只有来...请任何人帮助

这是我的代码



 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();
                    }

                }
            });
        }




在上面的代码中,Header []会自动在onSuccess方法中删除。如何解决它。请有人帮帮我!!

3 个答案:

答案 0 :(得分:2)

首先确保您拥有清单上的权限:

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

现在第二个是我建议您使用Volley请求。它易于使用,如果您使用的是Android工作室,则可以更轻松地插入库。只需将此行添加到app.gradle依赖项中,就可以了。

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

有关镜像库的详细信息,请单击here

现在用于示例实现:

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

并取消您的请求

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

为了便于处理,您需要更改要显示的片段,只需在暂停或停止时添加。古德勒克!

答案 1 :(得分:0)

我认为你正在使用LoopJ库,这很好,如果你这样做,坚持使用它。

您正在使用JsonHttpResponseHandler,而是使用AsyncHttpResponseHandler。响应将以字节数组的形式返回,因此您需要将其解析为json。我在这里创建它作为单独的功能,以便于重用。例如:

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://192.168.2.2:9999/useraccount/login/dologin", params, new AsyncHttpResponseHandler() { //here is where you should use AsyncHttpResponseHandler instead

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] response) {
            Log.d("*** LOG login: " + this.getClass().getName(), "SUCCESS");

            JSONObject responseParsed = parseResult(response);

            //your code continue here, example hide the progress bar
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
            Log.d("*** LOG error: " + this.getClass().getName(), e.toString());
        }

    });

然后是解析响应字节数组的示例代码。该函数从前一个onSuccess()内部调用:

 /**
 * Parse the byte[] that is returned from the server first into a string then cast the results string into a json object. 
 * This is wrapped inside a seperate function so it can be used by multiple calls.
 * @param response
 * @return
 */
JSONObject parseResult(byte[] response) {
    String str = null;
    try {
        str = new String(response, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    JSONObject responseToJson = null;
    try {
        responseToJson = new JSONObject(str);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return responseToJson;
}

答案 2 :(得分:0)

要从服务器获取数据,请按照此处的步骤进行操作

首先在build.gradle文件中添加此依赖项并同步它 编译'com.mcxiaoke.volley:library-aar:1.0.0'

现在创建一个名为Appcontroller的类,它扩展Application并添加它并导入那些显示红线的api

public class AppController extends Application {

public static final String TAG = AppController.class.getSimpleName();


private RequestQueue mRequestQueue;

private static AppController mInstance;

@Override
public void onCreate() {
    super.onCreate();
    mInstance = this;


}

public static synchronized AppController getInstance() {
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());


    }

    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    int socketTimeOut = 60000;
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeOut, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    req.setRetryPolicy(policy);
    getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
    req.setTag(TAG);
    getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(tag);
    }
}

public static String getDate() {
    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    Date date = new Date();
    String formatedDate = dateFormat.format(date);
    return formatedDate;
}
}

现在将这两个添加到您的活动

 Response.Listener<String> jsonResponse;
    Response.ErrorListener errorListener;

并在oncreate中初始化那些

    jsonResponse = new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Log.d("Response", response);

        //parseData(response); and store it


    }
};

    errorListener = new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError volleyError) {
        Toast.makeText(getApplicationContext(), "Unable to fetch Data from server", Toast.LENGTH_SHORT).show();
        finish();
    }
};


    if (ServerConfig.isNetworkOnline(SplashScreen.this)) {
        StringRequest strReq = new StringRequest(Request.Method.POST, "your server link", serverResponse, errorListener) {
        };
        AppController.getInstance().getRequestQueue().add(strReq);
    } else {
        Toast.makeText(getApplicationContext(), "Please check your network connection", Toast.LENGTH_SHORT).show();
        finish();
    }

如果问题让我知道并且不要忘记将Appcontroller添加到您的清单

<application
android:name=".AppController"..../>