安卓常用网络请求框架XUtils、OkHttp、Volley、Retrofit(1)

//这里修改成你要请求的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

  • 12
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值