按照步骤进行:
第一图
:
第二图
第三图
第四图:
以上步骤做完在app-->build.gradle中会添加一条
compile 'com.squareup.okhttp:okhttp:2.7.5'
到此集成okhttp就完成了,下面是使用方法
第一种不带参数方式,
1,构造一个OKHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
2,创建一个Request对象
Request request = new Request.Builder().url(url).get().build();
注意:括号中的url就是你请求数据的url
3,okHttpClient 对象去构造得到一个Call对象,去异步请求
okHttpClient.newCall(request).enqueue(new Callback() {});
代码如图:
OkHttpClient okHttpClient = new OkHttpClient();Request request = new Request.Builder().url(" 如:https://github.com/Android").build();Call call = okHttpClient.newCall(request);call.enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(Response response) throws IOException { }});
第二种带参数的方式
private class GetAsyncTask extends AsyncTask<Void, Void, String> {
//帐号
private String name;
//密码
private String paw;
String responseData = null;
private GetAsyncTask(String str1, String str2) {
name = str1;
paw = str2;
}
@Override
protected String doInBackground(Void... params) {
Response response = null;
OkHttpClient okHttpClient = new OkHttpClient();
//建立请求表单,添加上传服务器的参数
RequestBody formBody = new FormEncodingBuilder()
.add("userName", name)
.add("userPassword", paw)
.build();
//发起请求
Request request = new Request.Builder()
.url(ServerInterface.LOGIN)
.post(formBody)
.build();
try {
response = okHttpClient.newCall(request).execute();
responseData = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return responseData;
}
@Override
protected void onPostExecute(String s) {
//服务器返回的数据 s
LoginRegistrationDataBean json =
new Gson().fromJson(s, LoginRegistrationDataBean.
class);
String message = json.message;
if (message.equals("登录成功")) {
} else {
ToastUtil.showShort(LoginActivity.this, "用户名或密码错误");
}
super.onPostExecute(s);
}
}
注意:okhttp依赖okio库,所以还需要集成一个
compile 'com.squareup.okio:okio:1.13.0'