Android应用开发--Http
来源:互联网 发布:知满天教育培训怎么样 编辑:程序博客网 时间:2024/04/30 03:49
一: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 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"
);
0 0
- Android应用开发--Http
- 【Android应用开发技术:网络通信】Android HTTP编程
- vc++开发http应用
- linux应用开发-HTTP
- Android开发注意事项 HTTP
- 【Android 应用开发】Android 平台 HTTP网速测试 案例 API 分析
- android scoket http 应用范围
- java android HTTP应用程序设计
- Android Http的多线程应用
- android开发--android-async-http
- Android应用开发之通过HTTP协议发送XML数据并调用
- 【Android开发】网络编程及Internet应用-通过HTTP访问网络
- iOS开发中HTTP协议的应用
- HTTP协议在前端开发中的应用
- Android应用开发
- Android应用开发详解
- Android应用开发
- Android应用开发详解
- 软件自动更新提示和安装
- stdint.h 文件 int8_t uint8_t int16_t uint16_t (一)
- socketpair理解
- MacBook如何设置一键锁屏或者快捷锁屏?
- 【剑指offer】题目1508:把字符串转换成整数
- Android应用开发--Http
- 外观模式c++代码实现
- 优游娱乐总代上哪找啊【总代Q941494533】惩
- Mac Terminal 笔记
- 数据结构伪C代码:4.串
- 优游平台总代【总代Q941494533】簇
- 优游平台总代发放高点【总代Q941494533】啥
- 优游娱乐总代优博总代【总代Q941494533】科
- Create custom dialogs for use in your Visual Studio Setup projects