3
我正在使用以下代码进行api调用,并根据收到的响应将用户引导至页面。我如何检查互联网连接?检查互联网连接OKHTTP
我使用的是OK的HTTP客户端和我的代码如下所示:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = "https://xxxxxxxx/" + orderLineId;
JSONObject jSon = new JSONObject();
try {
jSon.put("prescription_xxxxx", prescriptionIntervalId);
jSon.put("prescription_xxxxxxx", false);
} catch (JSONException e) {
e.printStackTrace();
}
String data = jSon.toString();
RequestBody body = RequestBody.create(JSON, data);
Request request = new Request.Builder()
.url(url)
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", token)
.addHeader("Accept", "application/json")
.put(body)
.build();
client.newCall(request).enqueue(new Callback() {@Override
public void onFailure(Request request, IOException e) {
AlertDialog.Builder dialog = new AlertDialog.Builder(AutoRefillActivity.this);
dialog.setMessage("Something went wrong. Check connection.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
onBackPressed();
}
});
AlertDialog alert = dialog.create();
alert.show();
}
@Override
public void onResponse(Response response) throws IOException {
if(response.code()==401){
AlertDialog.Builder dialog = new AlertDialog.Builder(AutoRefillActivity.this);
dialog.setMessage("Device was idle for too long please login again.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
onBackPressed();
}
});
AlertDialog alert = dialog.create();
alert.show();
}
else {
Intent paymentSummary = new Intent(AutoRefillActivity.this,PPPaymentSummaryActivityNew.class);
paymentSummary.putExtra(PPPaymentSummaryActivityNew.EXTRA_ORDER,String.valueOf(orderLineId));
paymentSummary.putExtra("order_line_id",orderLineId);
paymentSummary.putExtra(PPPaymentSummaryActivityNew.EXTRA_CATEGORY_CODE,categoryCode);
paymentSummary.putExtra("prescriptionIntervalId",prescriptionIntervalId);
paymentSummary.putExtra("available",available);
paymentSummary.putExtra("token",token);
Bundle newBundle = new Bundle();
newBundle.putParcelable(PPPaymentSummaryActivityNew.EXTRA_PRODUCT,product);
paymentSummary.putExtras(newBundle);
startActivity(paymentSummary);
}
}
虽然我已经把一个警告框在onFailure处异步请求。这是行不通的。我仍然可以关闭互联网和我的应用程序崩溃。任何解决方案?
嗨,你有没有解决HttpStatusCode问题?我遇到了同样的问题......谢谢。 –