在MainActivity中使用OkHttp时出错“未处理的异常:java.io.IOException”

时间:2015-09-08 17:39:36

标签: android ioexception okhttp main-activity

错误出现在// Response response = client.newCall(request).execute();         return response.body()。string(); // lines。 整个代码: `

OkHttpClient client = new OkHttpClient();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String run(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }
}`

我应该在哪里写下我输入的网址?在OkHttp文档中,它仅针对公共类显示。如果我在MainActivity中使用它,我应该在哪里编写代码:

public static void main(String[] args) throws IOException{ OkHttpexample okHttpexample = new OkHttpexample(); String response = okHttpexample.run("https://raw.github.com/square/okhttp/master/README.md"); System.out.println(response);}

如果您对OkHttp有更详细的教程,那将非常有用

2 个答案:

答案 0 :(得分:2)

供您参考:

public class MainActivity extends AppCompatActivity {

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

    new APIRequest().execute();
}    

private class APIRequest extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... voids) {
        String response;
        try {
            // HTTP GET
            GetExample example = new GetExample();
            response = example.run("http://192.168.1.100/api/getsomething");                
        } catch (IOException e) {
            response = e.toString();
        }
        return response;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        // do something...
    }
}

public class GetExample {
    final OkHttpClient client = new OkHttpClient();

    String run(String url) throws IOException {
        try {
            Request request = new Request.Builder()
                    .url(url)
                    .build();                
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {                
            return e.toString();
        }
    }
}    
}

答案 1 :(得分:1)

您可能需要抓住IOException,尝试使用Try / Catch参与您的HTTP调用。

Try {
    Request request = new Request.Builder() 
            .url(url)
            .build(); 
    Response response = client.newCall(request).execute();
    return response.body().string();
} catch (IOException exception) {
}

在执行此操作时,请从方法声明中删除throws IOException