您的位置:首页 > 理论基础 > 计算机网络

android okhttp的简单使用(get,post)

2017-03-27 16:00 501 查看
添加依赖

compile 'com.squareup.okhttp3:okhttp:3.6.0'

Get请求

private void initGetOkHttp(){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.get()
.url("https:www.baidu.com")
.build();
Call call = client.newCall(request);
//异步调用,并设置回调函数
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(OkHttpActivity.this, "get failed", Toast.LENGTH_SHORT).show();
}

@Override
public void onResponse(Call call, final Response response) throws IOException {
final String res = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.e("--->","====> get" + res);
}
});
}
});
}

Post请求

private void initPostOkHttp(){
OkHttpClient client = new OkHttpClient();
FormBody formBody = new FormBody.Builder()
.add("username", "admin")
.add("password", "admin")
.build();
final Request request = new Request.Builder()
.url("http://www.jianshu.com/")
.post(formBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(OkHttpActivity.this, "Post Failed", Toast.LENGTH_SHORT).show();
}

@Override
public void onResponse(Call call, Response response) throws IOException {
final String res = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.e("--->","====> post" + res);
}
});
}
});
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android OkHttp