OkHttp是一个强大实用的网络请求框架,由伟大的Square创建,因为我们做安卓开发的,一定是用过Square发布的开源框架。
官网地址http://square.github.io/okhttp/,对应 Github地址:https://github.com/square/okhttp
public class OkHttpActivity extends AppCompatActivity {
private final static String TEST_GET_URL = "https://api.github.com/users/ldm520/repos";
private static final String TEST_POST_URL = "http://192.168.2.13:8083/app";
//请求结果数据展示
private TextView result_tv;
private final static int REQUEST_SUCCESS = 0;
private final static int REQUEST_FAIL = 1;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case REQUEST_SUCCESS://响应成功
String result = msg.obj.toString();
if (!TextUtils.isEmpty(result)) {
result_tv.setText("响应结果:\n");
result_tv.append(result);
}
break;
case REQUEST_FAIL://响应失败
Toast.makeText(OkHttpActivity.this, "网络请求失败", Toast.LENGTH_LONG).show();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ok_http);
result_tv = (TextView) findViewById(R.id.result_tv);
}
/**
* @description 使用OkHttp进行GET请求
* @author ldm
* @time 2017/5/2 10:02
*/
public void httpGet(View view) {
//创建okHttpClient对象
OkHttpClient client = new OkHttpClient();
//创建一个请求,传入请求地址
Request request = new Request.Builder()
.url(TEST_GET_URL)
.build();
//请求响应
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//请求失败
mHandler.sendEmptyMessage(REQUEST_FAIL);
}
//响应成功
@Override
public void onResponse(Call call, Response response) throws IOException {
Message msg = new Message();
msg.obj = response.body().toString();
msg.what = REQUEST_SUCCESS;
mHandler.sendMessage(msg);
}
});
}
/**
* @description 使用OkHttp进行POST请求
* @author ldm
* @time 2017/5/2 10:03
*/
public void httpPost(View view) {
OkHttpClient client = new OkHttpClient();
//构建请求体,传递参数
RequestBody body = new FormBody.Builder()
.add("userName", "ldm")
.add("passWord", "123456")
.build();
Request request = new Request.Builder()
.url(TEST_POST_URL)
.addHeader("", "")//这里添加Header信息
.post(body)//添加请求参数
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//请求失败
mHandler.sendEmptyMessage(REQUEST_FAIL);
}
//响应成功
@Override
public void onResponse(Call call, Response response) throws IOException {
Message msg = new Message();
msg.obj = response.body().toString();
msg.what = REQUEST_SUCCESS;
mHandler.sendMessage(msg);
}
});
}
}
记得添加网络权限。