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;
}
二: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>
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" ); |
相关文章推荐
- afinal - afinal 是一个android的 orm 和 ioc 框架。通过afinal的finalAcitivity,finalBitmap,finalDB,finalHttp,开发android应用将更加简单。 - Google Project Hosting
- 【Android 应用开发】Android 平台 HTTP网速測试 案例 API 分析
- 【Android 应用开发】Android 平台 HTTP网速测试 案例 API 分析
- Android入门前言(一)之------Android应用开发入门五问 (转自:http://blog.csdn.net/android_tutor/)
- Xamarin体验:使用C#开发iOS/Android应用(此文章为收藏博客,不是个人经验) by----作者:囧月 出处:http://lwme.cnblogs.com/
- 移动应用安全开发指南(Android)--完结篇(http://www.bubuko.com/infodetail-577312.html)
- 【Android 应用开发】Android 平台 HTTP网速测试 案例 API 分析
- Android应用开发网络请求 HttpClient和HttpURLConnection的区别
- 开发人员抱怨:Android应用程式钱难赚
- Google手机操作系统Android应用开发入门
- Google手机操作系统Android应用开发入门
- 简单介绍如何应用DDMS协助开发Android Apps
- Google手机操作系统Android应用开发入门
- 谷歌Android手机应用开发环境的搭建 推荐
- 谷歌Android手机应用开发环境的搭建
- 《Android 应用开发课程大纲》 V1.0
- 怎样开发适应不同分辨率的Android应用
- Google手机操作系统Android应用开发入门
- Google手机操作系统Android应用开发入门
- Google手机操作系统Android应用开发入门