从OKhttp获取字符串响应

时间:2017-01-08 07:49:59

标签: android

我想在建立连接后获得对主活动的字符串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; 
    }
}

4 个答案:

答案 0 :(得分:2)

这里的问题是了解异步任务的工作原理。当你调用client.newCall(request).enqueue(new Callback()时,它将在后台线程中运行(离开主线程),控制将传递到下一行return mJsonResponce;因此,总是 return null

您应该做的是传递一个回调方法,该方法将在响应成功时调用。您可以创建一个界面来返回结果:

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

在发出网络请求时传递此接口的对象,并在网络请求完成时调用适当的方法。

您需要注意的另一件事是OkHttp不会在主线程上返回响应,因此如果您要更新任何UI,则必须在UI /主线程上返回响应。这样的事情会起作用。

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

答案 1 :(得分:0)

您可以与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();
}

答案 2 :(得分:0)

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

答案 3 :(得分:-1)

更改此行

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

mJsonResponce=response.body().string();
希望能帮到你。