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

Android OkHttpClient

2017-03-23 12:05 369 查看
[POST]

private void VerifyUserCredential() {
String url= clsGlobal.ServiceUrl + "/test";

RequestBody body = new FormBody.Builder()
.add("username", username)
.add("password", password)
.build();
//addHeader根据Api是否需要Header参数
Request request = new Request.Builder()
.url(url)
.addHeader("store", store)
.post(body)
.build();

OkHttpClient client = new OkHttpClient();

client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();

MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "无法与服务器连接,请稍后再试!", Toast.LENGTH_LONG).show();
}
});
/* }*/
}

@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("", response.toString());

if(response.isSuccessful()) {
if(response.code() == 200) {
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
//成功
}
});

} else{
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
//可能返回204、等状态。可以用分开写
}
});
}
}else
{
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,"连接失败,请重新检查", Toast.LENGTH_LONG).show();
}
});
}
}
});
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android