我正在从 android 应用程序向 cgi php 服务器发出 HTTP 请求以获取 json 响应。我的应用程序在发出 HTTP 请求之前验证 Internet 连接是否可用。到目前为止,所有事情都正常工作。问题是我有时会因为发出 HTTP 请求后 Internet 连接突然中断而强制关闭。
所以我的问题是
- 我如何理解我收到了服务器的响应?
- 我是否需要为响应保留一个计时器?
我正在从 android 应用程序向 cgi php 服务器发出 HTTP 请求以获取 json 响应。我的应用程序在发出 HTTP 请求之前验证 Internet 连接是否可用。到目前为止,所有事情都正常工作。问题是我有时会因为发出 HTTP 请求后 Internet 连接突然中断而强制关闭。
所以我的问题是
这是我完美的网络请求处理运行代码
public JSONObject connectToService(String url, final Context context ) {
try {
if(!isConnected(context)){
return;
}
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpParams httpParameters = httpGet.getParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 7500;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 7500;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String jsonString = sb.toString();
Log.e("WebServiceHandler", "JSON string returned is"+jsonString.toString());
JSONObject jsonObject = new JSONObject(jsonString);
return jsonObject;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (SocketTimeoutException e) {
e.printStackTrace();
} catch (ConnectTimeoutException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public boolean isConnected(Context context) {
ConnectivityManager connMgr = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
} else {
return false;
}
}
此代码用于 GET 请求,如果您想使用 POST 请求访问 url,则只需相应地更改此行
HttpGet httpGet = new HttpGet(url);
和
HttpPost httpPost = new HttpPost(url);
首先将所有 HTTP 进程设置为 asyncTask,因为它可能会由于连接速度慢而导致 ANR(应用程序无响应)强制关闭,然后进行适当的异常处理。可以使用以下代码检查服务器响应:
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpGet httpget = new HttpGet(url + encodedData);
response = httpclient.execute(httpget);