0
我在使用OKHttp库时遇到了问题,我不确定它是代码问题还是图书馆以这种方式工作,但以下是我的webapi FullRest使用ASP.NET WEB Api并想要使用此服务,并且我能够轻松地创建POST和GET,问题是,如果我在m API中放置断点(如果android没有收到响应)那么4秒就会丢失,这并不好,因为想象一下,如果有人连接不好,而且Android必须等待一段时间才能收到用户的响应,那么我来自C#并且有一个等待很多的HttpClient类比在Android中接收响应的时间更长。这里是我的代码:如何处理在Android上使用OKHttp的响应时间
public class PostBase {
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static final MediaType urlEnconde = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
//private String Url="http://192.168.137.1:3000/";
OkHttpClient client = new OkHttpClient();
int POST(final PostModel model) throws IOException{
Gson gson = new Gson();
String modelJson = gson.toJson(model);
RequestBody body = RequestBody.create(JSON,modelJson);
Request request = new Request.Builder()
.url(URLb.GetUrl() + "api/gone/POST")
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.code();
}
我的活动:
public void MakePost(final PostModel model){
new AsyncTask<Void,Void,String>(){
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(SignUpActivity.this,R.style.Theme_MyDialog);
progressDialog.setMessage("Sending....");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
}
@Override
protected String doInBackground(Void... params) {
try{
PostBase postBase = new PostBase();
statusCode = postBase.POST(model);
if(statusCode == 201){
return "OK";
}
if(statusCode == 409){
return "Conflict";
}
else {
return "ERROR";
}
}catch (IOException e){
e.printStackTrace();
return "ERROR";
}
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
switch (s) {
case "OK":
progressDialog.dismiss();
AlertDialog.Builder builder1 = new AlertDialog.Builder(SignUpActivity.this);
builder1.setTitle("Gone");
builder1.setMessage("Fine");
builder1.setCancelable(true);
builder1.setPositiveButton(
"ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
//finish();
break;
case "Conflict":
progressDialog.dismiss();
new DialogMessage(SignUpActivity.this, "already exist");
break;
default:
progressDialog.dismiss();
new DialogMessage(SignUpActivity.this, "something went wrong");
break;
}
}
}.execute();
}
谢谢!
有没有这样的方法... –
对不起,试试吧 OkHttpClient eagerClient = client.newBuilder() .readTimeout(500,TimeUnit.MILLISECONDS) .build( ); – Pein