-1

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

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

我应该在哪里写我输入的url地址?在 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 的详细教程,那将会很有用

4

2 回答 2

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();
        }
    }
}    
}
于 2015-09-09T09:28:51.100 回答
1

您可能需要IOException使用 Try/Catch 捕获 , try 涉及您的 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从你的方法声明中删除。

于 2015-09-08T17:41:56.497 回答