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