简体   繁体   English

从OKhttp获取字符串响应

[英]getting String response from OKhttp

I want to get string JSON response to the main activity after making the connection I know it is running in different thread so please help me how I can get it and then return it from this method; 我想在建立连接后获得对主要活动的字符串JSON响应,我知道它在不同的线程中运行,所以请帮助我如何获取它,然后从该方法返回它;

public class MakeNetworkConnection {

    private String mBaseUrl;
    private String mApiKey;
    private String mContentType;
    private String mJsonResponce;

    public MakeNetworkConnection(String baseUrl, String apiKey, String contentType) {
        mBaseUrl = baseUrl;
        mApiKey = apiKey;
        mContentType = contentType;
    }
    public String startNetworkConnection() throws IOException {

        OkHttpClient client=new OkHttpClient();
        Request request=new Request.Builder().url("http://content.guardianapis.com/sections?api-key=1123456").build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.isSuccessful()){
                    mJsonResponce=response.body().string();
                }
            }
        });

       return mJsonResponce; 
    }
}

The problem here is about understanding how asynchronous tasks work. 这里的问题是关于了解异步任务如何工作。 When you are calling client.newCall(request).enqueue(new Callback() , it will run in the background thread (off the main thread) and control will pass to the next line which is return mJsonResponce; And thus, it will always return null . 当您调用client.newCall(request).enqueue(new Callback() ,它将在后台线程中运行(在主线程之外),并且控制权将传递到return mJsonResponce;的下一行return mJsonResponce;因此,它将始终返回null

What you should do is to pass a callback method which will be called when the response is successful. 您应该做的是传递一个回调方法,该方法将在响应成功时被调用。 You can create an interface to return the result: 您可以创建一个接口以返回结果:

public interface NetworkCallback {
   void onSuccess(String repsonse);
   void onFailure();
}

Pass an object of this interface while making the network request and call appropriate method when network request finishes. 在发出网络请求时传递此接口的对象,并在网络请求完成时调用适当的方法。

One more thing you will have take care is that OkHttp doesn't return the response on the main thread so you will have to return the response on UI/main thread if you are going to update any UI. 您还要注意的另一件事是, OkHttp不会在主线程上返回响应,因此,如果您要更新任何UI,则必须在UI /主线程上返回响应。 Something like this will work. 这样的事情会起作用。

@Override
public void onResponse(Call call, Response response) throws IOException {
      if(response.isSuccessful()){
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                       @Override
                       public void run() {
                          //return response from here to update any UI
                          networkCallback.onSuccess(response.body().string());
                       }
               });
      }
}

Instead of using calls asynchronously, you could use it synchronously with execute() . 您可以与execute()同步使用,而不是异步使用调用。

public String startNetworkConnection() throws IOException {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
                 .url("http://content.guardianapis.com/sections?api-key=1123456")
                 .build();
    return client.newCall(request)
                 .execute()
                 .body()
                 .string();
}

after advice from Rohit Arya i did the following: 根据Rohit Arya的建议,我做了以下工作:

public class OkHttpUtil {


public interface OKHttpNetwork{
     void onSuccess(String body);
     void onFailure();
}

public void startConnection(String url, final OKHttpNetwork okHttpCallBack) throws IOException {
    OkHttpClient client=new OkHttpClient();
    Request request=new Request.Builder()
            .url(url)
            .build();
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()){

                okHttpCallBack.onSuccess(response.body().string());
                }
            }
        });
    }
}

in the MainActvity i did the following : 在MainActvity中,我执行了以下操作:

        OkHttpUtil okHttpUtil=new OkHttpUtil();
    try {
        okHttpUtil.startConnection("http://content.guardianapis.com/sections?api-key=8161f1e9-248b-4bde-be68-637dd91e92dd"
                , new OkHttpUtil.OKHttpNetwork() {
                    @Override
                    public void onSuccess(String body) {
                        final String jsonResponse=body;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //show the response body
                                Toast.makeText(MainActivity.this,jsonResponse, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onFailure() {
                    //do something
                    }
                });
    } catch (IOException e) {
        e.printStackTrace();
    }

Change this line 更改此行

mJsonResponce=response.body().toString();

To

mJsonResponce=response.body().string();

Hope help you. 希望对你有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM