Vis*_*jay 1 android http internet-connection forceclose
我正在从android应用程序向cgi php服务器发出HTTP请求以获取json响应.我的应用程序在发出HTTP请求之前验证Internet连接是否可用.所有事情都正常运作.问题是我因为在发出HTTP请求后突然死于互联网连接而逐渐关闭.
所以我的问题是
小智 5
这是我完美的Web请求处理运行代码
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;
}
}
Run Code Online (Sandbox Code Playgroud)
此代码用于GET请求,如果您想使用POST请求命中url,则只需相应地更改此行
HttpGet httpGet = new HttpGet(url);
Run Code Online (Sandbox Code Playgroud)
同
HttpPost httpPost = new HttpPost(url);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7266 次 |
| 最近记录: |