http://square.github.io/okhttp/#download
https://repo1.maven.org/maven2/com/squareup/okio/okio/1.13.0/okio-1.13.0.jar
添加这两个包
2、get请求
public void click(View v) {
sendOkhttpRequest("https://www.baidu.com", new Callback() {
@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
String body = arg1.body().string();
System.out.println(body);
}
@Override
public void onFailure(Call arg0, IOException arg1) {
// TODO Auto-generated method stub
}
});
}
public void sendOkhttpRequest(String url,okhttp3.Callback callback) {
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(callback);
}
onResponse回调的参数是response,通过response.body().string()
获取字符串;如果希望获得返回的二进制字节数组,则调用response.body().bytes()
;如果你想拿到返回的inputStream,则调用response.body().byteStream()
onResponse
执行的线程并不是UI线程