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

Android HttpURLConnection和HttpClient获取网络内容

2013-06-15 15:01 585 查看
Android开发网络相关应用,可以用HttpURLConnection和HttpClient这两个类来

获取网络相关内容。

1、用HttpURLConnection获取网络内容

核心代码如下,网络内容用string content返回:

public static String getContent(String url) throws Exception{

// URL

URL Url = new URL(url);

// HttpURLConnection

HttpURLConnection httpconn = (HttpURLConnection) Url.openConnection();

//连接 超时时间

httpconn.setConnectTimeout(3000);

//Socket 超时时间

httpconn.setReadTimeout(5000);

String content = "";

if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK)
{


// InputStreamReader

InputStreamReader isr = new InputStreamReader(httpconn.getInputStream(),
"utf-8");


//int len = httpconn.getContentLength();

//System.out.printf("len[%d]\n",len);

//read type 1

int i;

while ((i = isr.read()) != -1) {

content = content (char) i;

}

isr.close();

}

//disconnect

httpconn.disconnect();

return content;

}

2、用HttpClient获取网络内容

核心代码如下,网络内容用string content返回:

public static String getContent(String url) throws Exception{

StringBuilder
sb = new StringBuilder();


DefaultHttpClient
client = new DefaultHttpClient();


HttpParams
httpParams = client.getParams();


//连接 超时时间

HttpConnectionParams.setConnectionTimeout(httpParams,
3000);


//Socket 超时时间

HttpConnectionParams.setSoTimeout(httpParams,
5000);


HttpResponse
response = client.execute(new HttpGet(url));


HttpEntity
entity = response.getEntity();


if
(entity != null) {


BufferedReader
reader =


new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 8192);

String
line = null;


while
((line = reader.readLine())!= null){


sb.append(line
"\n");


}

reader.close();

}

return
sb.toString();


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