这是 okhttp :
中的简单GET方法OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
我把这段代码放在主java文件中。
那么我应该把它调用到onCreate方法中呢?
我不知道如何使用它。例如,我想在按钮的onclicklistener中使用它。
答案 0 :(得分:1)
如果您使用的是eclipse,则必须下载okHttp jar文件并将其包含在项目中,或者如果您使用的是android studio,则在build.gradle中添加依赖项。您可以在此处找到相关说明 - http://square.github.io/okhttp/
最好为网络创建一个公共Util类,并编写常见方法HTTP请求(GET,POST等),以便只需传递所需的参数即可从应用程序中的任何位置调用它们。
现在,如果您愿意,可以将其添加到onclicklistener
示例 -
public class GetExample {
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public static void main(String[] args) throws IOException {
GetExample example = new GetExample();
String response = example.run("https://raw.github.com/square/okhttp/master/README.md");
System.out.println(response);
}
}
对于onClickListener,您可以在AsyncTask或新线程中编写以下代码(我希望您知道如何编写AsyncTask或新线程) -
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
String reponse = response.body().string();