//这里修改成你要请求的Url
String mBaseUrl=“http://47.101.204.40:8080/app_housework/user_login”;
FormEncodingBuilder requestBodyBuilder=new FormEncodingBuilder();
//构造你自己需要的 requestBody
RequestBody requestBody=requestBodyBuilder.add(“phoneNumber”,phoneNum).add(“password”,psw).build();
Request.Builder builder=new Request.Builder();
Request request = builder.url(mBaseUrl).post(requestBody).post(requestBody).build();
Call call=okHttpClient.newCall(request);
//返回信息
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
//输出出错信息
L.e(“onFailure:”+e.getMessage());
e.printStackTrace();
}
@Override
public void onResponse(final Response response) throws IOException {
// Gson gson=new Gson();
final String res=response.body().string();
Log.i(“denglu”, res);
//需捕获异常
try{
Gson gson=new Gson();
Type type = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> sList = gson.fromJson(res, type);
final String result= sList.get(“message”).toString();
Log.i(“res”,result);
if(res.equals(“unexisted”)){
toast(“该账号尚未注册!”);
}
runOnUiThread(new Runnable() {
@Override
public void run() {
SharedPreferences sp=getSharedPreferences(“data”, MODE_PRIVATE);
long errorTime=sp.getLong(“errorTime”, 0L);//输入错误时的时间
long recentTime=System.currentTimeMillis();//获取当前时间
if (result.equals(“success”)&&recentTime-errorTime>WAIT_TIME) {
//成功登陆 跳转
LoginActivity.this.startActivity(intentindex);
LoginActivity.this.finish();
} else {
//登录失败
}
}
}
);//线程结束
}catch(Exception e){
e.printStackTrace();
toast(“服务器返回错误”);
}
}
});//正确返回结束
常见问题(1):
已经导入最新的包,但是okhttp的Request.Builder().url().buid()的Builder()不存在怎么办?
OkHttpClient okHttpClient = new OkHttpClient();
final okhttp3.Request request = new okhttp3.Request.Builder().url(url) .build();
解决:你需要前面加上包名就可以了
常见问题(2):
运行到response.body().string()一步时抛异常
java.lang.IllegalStateException: closed
具体的意思就是
The IllegalStateException arises because the HttpConnection seems to be closed when trying to use it. Could it be because you are calling twice the method response.body()?
调用response.body().string()的时候数据流已经关闭
解决:用一个变量存储你要打印的就可以,不要直接打印出来
3.Volley
Volley是Google官方出的一套小而巧的异步请求库,该框架封装的扩展性很强,支持Http