您的位置:首页 > 理论基础 > 计算机网络

判断网络是否可用

2014-12-04 22:28 176 查看
1. **1.判断网络是否可用:**

---------------

private boolean isNet(Context context) {

ConnectivityManager con = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo networkinfo = con.getActiveNetworkInfo();

if (networkinfo == null || !networkinfo.isAvailable()) {

// 当前网络不可用

return false;

}

return true;

}

1. **post requets**

----------------

public String connect(String url, Map<String, Object> values, Context context) {

if (!isNet(context)) {

return "";

}

HttpClient httpClient = getHttpClient();

String result = "";

HttpPost httpPost = new HttpPost(url);

HttpResponse httpResponse = null;

List<NameValuePair> parameters = new ArrayList<NameValuePair>();

if (values != null && !values.isEmpty()) {

// if (!CompareUtils.isEmpty(values)) {

Set<Entry<String, Object>> set = values.entrySet();

for (Entry<String, Object> entry : set) {

parameters.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));

}

}

try {

Log.i("tag", "jsonParam" + parameters.toString());

httpPost.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8));

httpResponse = httpClient.execute(httpPost);

int code = httpResponse.getStatusLine().getStatusCode();

if (code == HttpStatus.SC_OK) {

result = EntityUtils.toString(httpResponse.getEntity());

Log.i("tag", "jsonResult" + result.toString());

} else {

Log.i("json_error", url + "____网络:" + httpResponse.getStatusLine().getStatusCode());

}

} catch (ConnectTimeoutException e) {

e.printStackTrace();

return "";

} catch (SocketTimeoutException e) {

e.printStackTrace();

return "";

} catch (Exception e) {

e.printStackTrace();

return "";

} finally {

httpClient.getConnectionManager().shutdown();

}

return result;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: