HC_Get+net
package com.baidu.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class MyUtil {
// public static final String URL_1 = ""
public static boolean isNetAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo == null || !networkInfo.isAvailable()) {
return false;
}
return true;
}
public static String getJsonFromServer(String URL) {
StringBuffer sb = new StringBuffer();
try {
URL url = new URL(URL);
HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
urlcon.setConnectTimeout(5000);
urlcon.setReadTimeout(5000);
if (urlcon.getResponseCode() == 200) {
BufferedReader br = new BufferedReader(new InputStreamReader(
urlcon.getInputStream(), "gbk"));
String str = "";
while ((str = br.readLine()) != null) {
sb.append(str);
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
};
// /////////////////////////////////////////////////////////////////////////////
public static String getdataByClient(String url) {
String data = "";
// 创建get请求对象
HttpGet get = new HttpGet(url);
// 设置情亲参数
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);
// 创建执行请求的对象
HttpClient client = new DefaultHttpClient(params);
// 执行请求参数
try {
HttpResponse resp = client.execute(get);
// 判断是否执行成功
if (resp.getStatusLine().getStatusCode() == 200) {
// 获取响应的数据
HttpEntity entity = resp.getEntity();
// 将数据转化为字符串
data = EntityUtils.toString(entity, "gbk");
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data;
}
}