这是我从PHP服务器获取JSON字符串的代码。

当我运行此应用程序时,它崩溃并说Response response = client.newCall(request).execute();存在错误
我究竟做错了什么?

public class MainActivity extends Activity {

    //private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new AsyncTask<Void, Void, String>(){

            @Override
            protected String doInBackground(Void... params) {

                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url)
                        .build();

                try {
                    Response response = client.newCall(request).execute();
                    Log.d("OkHttp", "doInBackground() called with: " + "params = [" + response.body().string() + "]");
                    return response.body().string();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }.execute();
    }
}

最佳答案

您无需将其置于异步任务中,因为您可以使用本身就是异步的OKHttp库的回调。
第二件事是您使用了错误的方法。代替execute(),您应该使用enqueue(),它具有一个回调作为参数,如上所述。


试试这个代码:

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
                  .url(url)
                  .build();
Call call = client.newCall(request);
call.enqueue(new Callback() {

    @Override
    public void onFailure(Call call, IOException e) {

        // Observe reason of failure using
        e.printStackTrace();
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
            if(response.isSuccessful()){
                // Use response here
            }
            else{
                // Observe error
            }
    }
});

关于android - Android上的OkHttp,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46104830/

10-10 06:23