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

Android应用开发--Http

2014-06-24 10:54 218 查看
一:JDK中HttpURLConnection

Get

URL url = new URL("string url"):
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(in);
StringBuffer strBuffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
strBuffer.append(line);
}
result = strBuffer.toString();
if (connection != null) {
connection.disconnect();
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}Post
public String executeHttpPost() {
String result = null;
URL url = null;
HttpURLConnection connection = null;
InputStreamReader in = null;
try {
url = new URL("string url");
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Charset", "utf-8");

//写入参数
DataOutputStream dop = new DataOutputStream(connection.getOutputStream());
dop.writeBytes("token=xxxxxxx");
dop.flush();
dop.close();

in = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(in);
StringBuffer strBuffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
strBuffer.append(line);
}
result = strBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}

URLDecoder.decode(
"测试"
,
"utf-8"
);

URLEncoder.encode(
"测试"
,
"utf-8"
)


二:Apache的HttpClient

Get

HttpGet get=new HttpGet("str url?name=xxx&pwd=xxx");
HttpClient cliet=new DefaultHttpClient();
try {
HttpResponse response=cliet.execute(get);
HttpEntity entity=response.getEntity();
InputStream is=entity.getContent();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line=null;
StringBuffer sb=new StringBuffer();
while((line=br.readLine())!=null){
sb.append(line);
}
System.out.println(sb.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Post

//创建默认的客户端对象
HttpClient cliet=new DefaultHttpClient();
//用list封装要向服务器端发送的参数
List<BasicNameValuePair> pairs=new ArrayList<BasicNameValuePair>();
pairs.add(new BasicNameValuePair("name", "xxx"));
pairs.add(new BasicNameValuePair("pwd", "xxx"));
try {
//用UrlEncodedFormEntity来封装List对象
UrlEncodedFormEntity urlEntity=new UrlEncodedFormEntity(pairs);
//设置使用的Entity
post.setEntity(urlEntity);
try {
//客户端开始向指定的网址发送请求
HttpResponse response=cliet.execute(post);
//获得请求的Entity
HttpEntity entity=response.getEntity();
InputStream is=entity.getContent();
//下面是读取数据的过程
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line=null;
StringBuffer sb=new StringBuffer();
while((line=br.readLine())!=null){
sb.append(line);
}
System.out.println(sb.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

三- 超时Sample
<span style="color:#404040;">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
c805
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();
</span><span style="color:#cc0000;"> client.getParams().setIntParameter(
HttpConnectionParams.SO_TIMEOUT, TIME_OUT_DELAY); // 超时设置
client.getParams().setIntParameter(
HttpConnectionParams.CONNECTION_TIMEOUT, TIME_OUT_DELAY);// 连接超时 </span><span style="color:#404040;">
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;
}

} </span>

URLEncoder.encode(
"测试"
,
"utf-8"
)
2
URLDecoder.decode(
"测试"
,
"utf-8"
);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: