本文是收录的两篇关于这方面的文章
public static void main(String[] args){
long a=System.currentTimeMillis();
try{
URL myurl = new URL(“http://www.baidu.cn”);
URLConnection myurlcon = myurl.openConnection();
myurlcon.setConnectTimeout(1000);
myurlcon.setReadTimeout(1000);
BufferedReader in = new BufferedReader(new InputStreamReader(myurlcon.getInputStream(),”UTF-8″));
String inputLine;
while ((inputLine = in.readLine()) != null){
System.out.println(inputLine);
in.close();
System.out.println(System.currentTimeMillis()-a);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private class XmlAsyncLoader extends XmlResourceRequest {
private boolean mIsCancle = false;
private HttpGet mGet;
private HttpClient mHttp;
public XmlAsyncLoader(MxActivity> activity, String url)
throws MalformedURLException {
super(activity, url);
}
@Override
protected void doTaskInBackground() {
// 请求数据
if (mUrl.toLowerCase().startsWith("http://")) {
mGet = initHttpGet(mUrl);
mHttp = initHttp();
try {
HttpResponse response = mHttp.execute(mGet);
if (mIsCancle) {
return;
}
if (response != null) {
if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){
onResponseError("network error");
Log.v(TAG, "the code is :"+response.getStatusLine().getStatusCode());
return;
}
notifyUpdateProgress(70);
Document doc = getDocumet(response);
Element root = doc.getDocumentElement();
NodeList appList = root
.getElementsByTagName(Item_ELEMENT_NAME);
final int len = appList.getLength();
if (len <= 0) {// 没有items
onFoundNoItems();
return;
}
for (int i = 0; i < len; i++) {
Element item = (Element) appList.item(i);
if (item.getNodeType() == Node.ELEMENT_NODE) {
HahaItemInfo info = createHahaItemIno(item);
if (mIsCancle){
return;
}
onFoundItem(info, 80 + 20 * (i + 1) / len);
addUrlToQueue(info.userIconUrl);
}
};
}
}catch(ConnectTimeoutException e){
onResponseError("time out");
} catch (ClientProtocolException e) {
--mCurrentPage;
e.printStackTrace();
} catch (IOException e) {
--mCurrentPage;
e.printStackTrace();
} catch (XmlPullParserException e) {
--mCurrentPage;
e.printStackTrace();
}finally{
notifyLoadFinish();
notifyLoadImages();
mHttp.getConnectionManager().shutdown();
}
}
}
private HttpClient initHttp() {
HttpClient client = new DefaultHttpClient();
client.getParams().setIntParameter(
HttpConnectionParams.SO_TIMEOUT, TIME_OUT_DELAY); // 超时设置
client.getParams().setIntParameter(
HttpConnectionParams.CONNECTION_TIMEOUT, TIME_OUT_DELAY);// 连接超时
return client;
}
private HttpGet initHttpGet(String mUrl) {
HttpGet get = new HttpGet(mUrl);
initHeader(get);
return get;
}
@Override
public boolean tryCancel() {
Log.i(TAG, "tryCanle is working");
mGet.abort();
mIsCancle = true;
mHttp.getConnectionManager().shutdown();
notifyLoadFinish();
return true;
}
}
client.getParams().setIntParameter(
HttpConnectionParams.SO_TIMEOUT, TIME_OUT_DELAY); // 超时设置
client.getParams().setIntParameter(
HttpConnectionParams.CONNECTION_TIMEOUT, TIME_OUT_DELAY);// 连接超时
===============
public static HttpURLConnection openUrl(Context context, String urlStr) {
URL urlURL = null;
HttpURLConnection httpConn = null;
try {
urlURL = new URL(urlStr);
// 需要android.permission.ACCESS_NETWORK_STATE
// 在没有网络的情况下,返回值为null。
NetworkInfo networkInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
// 如果是使用的运营商网络
if (networkInfo != null) {
if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
// 获取默认代理主机ip
String host = android.net.Proxy.getDefaultHost();
// 获取端口
int port = android.net.Proxy.getDefaultPort();
if (host != null && port != -1) {
// 封装代理連接主机IP与端口号。
InetSocketAddress inetAddress = new InetSocketAddress(host, port);
// 根据URL链接获取代理类型,本链接适用于TYPE.HTTP
java.net.Proxy.Type proxyType = java.net.Proxy.Type.valueOf(urlURL.getProtocol().toUpperCase());
java.net.Proxy javaProxy = new java.net.Proxy(proxyType, inetAddress);
httpConn = (HttpURLConnection) urlURL.openConnection(javaProxy);
} else {
httpConn = (HttpURLConnection) urlURL.openConnection();
}
} else {
httpConn = (HttpURLConnection) urlURL.openConnection();
}
httpConn.setConnectTimeout(Const.NETWORK_OPEN_TIMEOUT);
httpConn.setReadTimeout(Const.NETWORK_READ_TIMEOUT);
httpConn.setDoInput(true);
} else {
// LogOut.out(this, "No Avaiable Network");
}
} catch (NullPointerException npe) {
npe.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return httpConn;
}