我正在网络服务中提出请求。
我如何测试服务器没有响应的情况(原因可能服务器已关闭)?
我的意思是我如何在模拟器上测试它?有没有办法可以发送请求并阻止响应以查看我的应用程序如何处理这种情况?在这种情况下我该怎么办?
答案 0 :(得分:1)
请考虑以下代码:
try {
DefaultHttpClient httpclient = getClient();
HttpGet request = new HttpGet();
SchemeRegistry schemeRegistry = httpclient
.getConnectionManager().getSchemeRegistry();
schemeRegistry.register(new Scheme("https",
new TlsSniSocketFactory(), 443));
URI website = new URI(getString(R.string.u3));
request.setURI(website);
HttpResponse response = httpclient.execute(request);
in = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
result = in.readLine();
// Log.d(TAG, "Version Check result = " + result);
} catch (Exception e) {
e.printStackTrace();
// Log.e(TAG, "Error in http connection " + e.toString());
}
你需要设置一个超时&当服务器关闭时,它可能会进入Catch块,你可以在服务器关闭时做任何你想做的事情/你没有收到服务器的响应
答案 1 :(得分:0)
StringRequest stringRequest=new StringRequest(Request.Method.POST,reg_url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONArray jsonArray=new JSONArray(response);
JSONObject jsonObject=jsonArray.getJSONObject(0);
String message=jsonObject.getString("message"); //message is to be send by server
builder.setTitle("Server Response");
Toast.makeText(this,message,Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});