public class MainActivity extends Activity {
protected static final int GET_JSON_STRING_OK = 0;
protected static final int GET_JSON_STRING_OK2 = 1;
private Context context;
private Handler hanlder = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case GET_JSON_STRING_OK :
Toast.makeText(context, (String) msg.obj, 0).show();
break;
case GET_JSON_STRING_OK2 :
Toast.makeText(context, (String) msg.obj, 0).show();
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
HttpClientGet("http://www.baidu.com", "UTF-8");
// HttpUrlConnGet("http://www.baidu.com","UTF-8");
}
private void HttpUrlConnGet(final String strurl, final String charset) {// 2.1HttpUrlConnGet
new Thread() {
public void run() {
try {
URL url = new URL(strurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(6000);
InputStream is = conn.getInputStream();
String string = inputStream2String(is, charset);// 2.0传入输入流,和编码,转换长字符串
Message msg = new Message();
msg.what = GET_JSON_STRING_OK2;
msg.obj = string;
hanlder.sendMessage(msg);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
};
}.start();
}
public static String inputStream2String(InputStream is, String charset) {// 2.0传入输入流,和编码,转换长字符串
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
int i = -1;
while ((i = is.read()) != -1) {
baos.write(i);
}
return baos.toString(charset);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != baos) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
baos = null;
}
}
return null;
}
private void HttpClientGet(final String strUrl, final String charset) {// 1.0HttpClient
new Thread() {
public void run() {
try {
HttpClient httpClient = new DefaultHttpClient(); // 1.0HttpClient对象
HttpGet request = new HttpGet(strUrl); // 1.1HttpGet对象
HttpResponse response = httpClient.execute(request); // 1.2获得HttpResponse对象
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 1.3请求200
String string = EntityUtils.toString(response.getEntity(), charset);// 1.4响应成字符串,设置编码
Message msg = new Message();// 1.5发送数据到UI线程更新
msg.what = GET_JSON_STRING_OK;
msg.obj = string;
hanlder.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}
//2秒按2次退出程序
private long first;
public void onBackPressed() {
long now = System.currentTimeMillis();
if (now - first >= 2000) {
first = now;
Toast.makeText(context, "再按一次退出程序", 0).show();
} else {
super.onBackPressed();
}
}
}
HttpUrlcon与HttpClinet(输入网络地址返回字符串,只实现Get方法)
最新推荐文章于 2024-07-31 18:23:27 发布