Android日常整理(二)---博客园接口、 HttpGet类和HttpPost类、ProgressDialog、dispatchKeyEvent

来源:互联网 发布:java 短链接生成 编辑:程序博客网 时间:2024/05/21 17:06

博客园客户端开发用到的接口(其实就是RSS)

提示:通过接口获取的数据均为xml数据,可以根据具体的xml结构来解析。

 

1.新闻目录

热门新闻:http://wcf.open.cnblogs.com/news/hot/10

数字表示当前页要加载的新闻数目

最近新闻:http://wcf.open.cnblogs.com/news/recent/10

数字表示当前页要加载的新闻数目

推荐新闻: http://wcf.open.cnblogs.com/news/recommend/paged/1/5

数字表示当前页要加载的新闻数目,可同过改变数字加载更多。

2.新闻内容

http://wcf.open.cnblogs.com/news/item/199054

数字表示要获取的当前新闻的id。

3.新闻评论

http://wcf.open.cnblogs.com/news/item/199054/comments/1/5

199054表示新闻id(新闻的id可以通过新闻目录接口获取的数据中获取),1表示评论的页数,5表示每页要加载的评论数。

4.博客目录

所有博客:1.http://wcf.open.cnblogs.com/blog/sitehome/recent/5。

2.http://wcf.open.cnblogs.com/blog/sitehome/paged/1/10

48小时阅读排行:http://wcf.open.cnblogs.com/blog/48HoursTopViewPosts/5

十天推荐排行: http://wcf.open.cnblogs.com/blog/TenDaysTopDiggPosts/5

5代表当前页要加载的数目,当前只能加一页,可以累加数字加载更多。

博客内容:http://wcf.open.cnblogs.com/blog/post/body/3535626

335626代表的博客的的id,博客id可以通过获取的博客目录中获得。

博客评论:http://wcf.open.cnblogs.com/blog/post/3535784/comments/1/5

335626代表的博客的的id,1代表页数,5代表当前页加载的评论数,可以他能够过改变1或者5来加载更多。

5.搜索博主

http://wcf.open.cnblogs.com/blog/bloggers/search?t=721881283

t后面跟的是博客园的帐号

 

 

android ImageButton默认在图片周围添加了白色的边框,很不好看,去掉它的方法:

android:background="#00ffffff" 

 

android 网络编程 HttpGet类和HttpPost类使用详解

虽然在登录系统中使用了Web Service与服务端进行交互。但是在传递大量的数量时,Web Service显得有些笨拙。在本节将介绍移动电子相册中使用的另外一种与数据库交互的方法。直接发送HTTP GET或POST请求。这就要用到HttpGet、HttpPost以及HttpURLConnection这些类。

HttpGet类和HttpPost类

本节将介绍Android SDK集成的Apache HttpClient模块。要注意的是,这里的Apache HttpClient模块是HttpClient 4.0(org.apache.http.*),而不是Jakarta Commons HttpClient 3.x(org.apache.commons.httpclient.*)。

在HttpClient模块中用到了两个重要的类:HttpGet和HttpPost。这两个类分别用来提交HTTP GET和HTTP POST请求。为了测试本节的例子,需要先编写一个Servlet程序,用来接收HTTP GET和HTTP POST请求。读者也可以使用其他服务端的资源来测试本节的例子。

假设192.168.17.81是本机的IP,客户端可以通过如下的URL来访问服务端的资源:

http://192.168.17.81:8080/querybooks/QueryServlet?bookname=开发

在这里bookname是QueryServlet的请求参数,表示图书名,通过该参数来查询图书信息。

现在我们要通过HttpGet和HttpPost类向QueryServlet提交请求信息,并将返回结果显示在TextView组件中。

无论是使用HttpGet,还是使用HttpPost,都必须通过如下3步来访问HTTP资源。

1.创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。

2.使用DefaultHttpClient类的execute方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象。

3.通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理。

如果使用HttpPost方法提交HTTP POST请求,还需要使用HttpPost类的setEntity方法设置请求参数。

本例使用了两个按钮来分别提交HTTP GET和HTTP POST请求,并从EditText组件中获得请求参数(bookname)值,最后将返回结果显示在TextView组件中。两个按钮共用一个onClick事件方法,代码如下:

public void onClick(View view)  

{  

    //  读者需要将本例中的IP换成自己机器的IP  

    String url = "http://192.168.17.81:8080/querybooks/QueryServlet";  

    TextView tvQueryResult = (TextView) findViewById(R.id.tvQueryResult);  

    EditText etBookName = (EditText) findViewById(R.id.etBookName);  

    HttpResponse httpResponse = null;  

    try  

    {  

        switch (view.getId())  

        {  

            //  提交HTTP GET请求  

            case R.id.btnGetQuery:  

                //  向url添加请求参数  

                url += "?bookname=" + etBookName.getText().toString();  

                //  第1步:创建HttpGet对象  

                HttpGet httpGet = new HttpGet(url);  

                //  第2步:使用execute方法发送HTTP 

GET请求,并返回HttpResponse对象  

                httpResponse = new DefaultHttpClient().execute(httpGet);  

                //  判断请求响应状态码,状态码为200表

示服务端成功响应了客户端的请求  

                if (httpResponse.getStatusLine().

getStatusCode() == 200)  

                {  

                    //  第3步:使用getEntity方法获得返回结果  

                    String result = EntityUtils.

toString(httpResponse.getEntity());  

                    //  去掉返回结果中的"\r"字符,

否则会在结果字符串后面显示一个小方格  

                    tvQueryResult.setText(result.replaceAll("\r", ""));  

                }  

                break;  

            //  提交HTTP POST请求  

            case R.id.btnPostQuery:  

                //  第1步:创建HttpPost对象  

                HttpPost httpPost = new HttpPost(url);  

                //  设置HTTP POST请求参数必须用NameValuePair对象  

                List<NameValuePair> params = new 

ArrayList<NameValuePair>();  

                params.add(new BasicNameValuePair

("bookname", etBookName.getText(). toString()));  

                //  设置HTTP POST请求参数  

                httpPost.setEntity(new 

UrlEncodedFormEntity(params, HTTP.UTF_8));  

                //  第2步:使用execute方法发送HTTP 

POST请求,并返回HttpResponse对象  

                httpResponse = new DefaultHttpClient().

execute(httpPost);  

                if (httpResponse.getStatusLine().

getStatusCode() == 200)  

                {  

                    //  第3步:使用getEntity方法获得返回结果  

                    String result = EntityUtils.toString

(httpResponse.getEntity());  

                    //  去掉返回结果中的"\r"字符,

否则会在结果字符串后面显示一个小方格  

                    tvQueryResult.setText(result.replaceAll("\r", ""));  

                }  

                break;  

        }  

    }  

    catch (Exception e)  

    {  

        tvQueryResult.setText(e.getMessage());  

}  

[转]Android Http get post请求

首先我们先了解下Get请求和Post请求的区别:

表单提交中get和 post方式的区别有5点:

1.get是从服务器上获取数据,post是向服务器传送数据。

2.get是把参数数据队列加到提交表单的 ACTION属性所指的URL中,值和表单内各个字段一一对应,在URL中可以看到。post是通过HTTPpost机制,将表单内各个字段与其内容放置在HTML HEADER内一起传送到ACTION属性所指的URL地址。用户看不到这个过程。

3.对于get方式,服务器端用 Request.QueryString获取变量的值,对于post方式,服务器端用Request.Form获取提交的数据。

4.get 传送的数据量较小,不能大于2KB。post传送的数据量较大,一般被默认为不受限制。但理论上,IIS4中最大量为80KB,IIS5中为100KB。

5.get安全性非常低,post安全性较高。

 

一、HttpClinet方式

1、HTTP GET 示例:

public class TestHttpGetMethod{  

     public void get(){  

         BufferedReader in = null;  

         try{  

            HttpClient client = new DefaultHttpClient();  

            HttpGet request = new HttpGet();  

            request.setURI("http://w26.javaeye.com");  

            HttpResponse response = client.execute(request);   

             in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));     

            StringBuffer sb = new StringBuffer("");   

            String line = "";  

            String NL = System.getProperty("line.separator");  

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

                sb.append(line + NL); 

            }  

            in.close();  

            String page = sb.toString();  

            Log.i(TAG, page);  

         }catch(Exception e){  

             Log.e(TAG,e.toString())  

         }finally{  

             if(in != null){  

                try{  

                     in.close();  

                 }catch(IOException ioe){  

                     Log.e(TAG, ioe.toString());  

                 }  

             }  

         }  

     }  

 }

带参数的 HTTP GET: 

HttpGet request = new HttpGet("http://www.baidu.com/s?wd=amos_tl");  

client.execute(request);

 

2、HTTP POST 示例:

public class TestHttpPostMethod{  

      public void post(){  

          BufferedReader in = null;  

          try{  

              HttpClient client = new DefaultHttpClient();  

              HttpPost request = new HttpPost("http://localhost/upload.jsp");   

              List<NameValuePair> postParams = new ArrayList<NameValuePair>();  

              postParams.add(new BasicNameValuePair("filename", "sex.mov"));  

              UrlEncodeFormEntity formEntity = new UrlEncodeFormEntity(postParams);  

             request.setEntity(formEntity);  

             HttpResponse response = client.execute(request);  

             in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));     

             StringBuffer sb = new StringBuffer("");   

             String line = "";  

             String NL = System.getProperty("line.separator");  

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

                 sb.append(line + NL);  

             }  

             in.close();  

             String result = sb.toString();  

             Log.i(TAG, result );  

         }catch(Exception e){  

             Log.e(TAG,e.toString())  

         }finally{  

             if(in != null){  

                 try{  

                     in.close();  

                 }catch(IOException ioe){  

                     Log.e(TAG, ioe.toString());  

                 }  

             }  

         }  

     } 

 }

 

二、HttpURLConnection 方式

  URL url = null;

  HttpURLConnection conn = null;

  InputStream in = null;

  OutputStream out = null;

  byte[] data ="测试字符串".getBytes();

  try{

     url =new URL("www.xxx.com/servlet");

     conn = (HttpURLConnection) url.openConnection();

  

    //设置连接属性

    conn.setDoOutput(true);// 使用 URL 连接进行输出

    conn.setDoInput(true);// 使用 URL 连接进行输入

    conn.setUseCaches(false);// 忽略缓存

    conn.setConnectTimeout(30000);//设置连接超时时长,单位毫秒

    conn.setRequestMethod("POST");//设置请求方式,POST or GET,注意:如果请求地址为一个servlet地址的话必须设置成POST方式

 //设置请求头

   conn.setRequestProperty("Accept", "*/*");

   conn.setRequestProperty("Connection", "Keep-Alive");

   conn.setRequestProperty("Accept-Charset", "utf-8");

   if (data != null) {

      out = conn.getOutputStream();

      out.write(data);

   }

   int code = conn.getResponseCode();

   if(code ==200){

      in = conn.getInputStream();// 可能造成阻塞

      long len = conn.getContentLength();

      byte[] bs = new byte[(int) len];//返回结果字节数组

      int all = 0;

   int dn = 0;

      while ((dn = in.read(bs, all, 1)) > 0) {

        all += dn;

        if (all == len) {

        break;

        }

      }

   }

 } 

======================================

那么接下来让我们看看在Android平台开发中如何执行一个Post请求:

以下是代码示例:

 package com.jixuzou.search;

 import java.util.ArrayList;

 import java.util.List;

 import org.apache.http.HttpResponse;

 import org.apache.http.NameValuePair;

 import org.apache.http.client.entity.UrlEncodedFormEntity;

 import org.apache.http.client.methods.HttpPost;

 import org.apache.http.impl.client.DefaultHttpClient;

 import org.apache.http.message.BasicNameValuePair;

 import org.apache.http.protocol.HTTP;

 import org.apache.http.util.EntityUtils;

 import android.app.Activity;

 import android.os.Bundle;

 import android.view.View;

 import android.view.View.OnClickListener;

 import android.widget.Button;

 public class mian extends Activity {

         /** Called when the activity is first created. */

         private Button btnTest;

         @Override

         public void onCreate(Bundle savedInstanceState) {

                 super.onCreate(savedInstanceState);

                 setContentView(R.layout.main);

                 btnTest = (Button) findViewById(R.id.Button01);

                 btnTest.setOnClickListener(new OnClickListener() {

                         @Override

                         public void onClick(View v) {

                                 getWeather();

                         }

                 });

         }

         private void getWeather(){

                 try {

                         final String SERVER_URL = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather"; // 定义需要获取的内容来源地址

                         HttpPost request = new HttpPost(SERVER_URL); // 根据内容来源地址创建一个Http请求

                         params.add(new BasicNameValuePair("theCityCode", "长沙")); // 添加必须的参数

                         params.add(new BasicNameValuePair("theUserID", "")); // 添加必须的参数

                         request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); // 设置参数的编码

                         HttpResponse httpResponse = new DefaultHttpClient().execute(request); // 发送请求并获取反馈

 // 解析返回的内容

                         if (httpResponse.getStatusLine().getStatusCode() != 404)

                         {

                                 String result = EntityUtils.toString(httpResponse.getEntity());

                                 System.out.println(result);

                         }

                 } catch (Exception e) {

                 }

         }

 }

 

 

setProgressStyle:设置进度条风格,风格为圆形,旋转的。 

setTitlt:设置ProgressDialog 标题 

setMessage:设置ProgressDialog提示信息; 

setIcon:设置ProgressDialog标题图标; 

setIndeterminate:设置ProgressDialog 的进度条是否不明确; 

setCancelable:设置ProgressDialog 是否可以按返回键取消; 

setButton:设置ProgressDialog 的一个Button(需要监听Button事件); 

show:显示ProgressDialog。

 

// 创建ProgressDialog对象  

xh_pDialog = new ProgressDialog(Activity01.this);  

// 设置进度条风格,风格为圆形,旋转的  

xh_pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);  

// 设置ProgressDialog 标题  

xh_pDialog.setTitle("提示");  

// 设置ProgressDialog提示信息  

xh_pDialog.setMessage("这是一个圆形进度条对话框");  

// 设置ProgressDialog标题图标  

xh_pDialog.setIcon(R.drawable.img1);  

// 设置ProgressDialog 的进度条是否不明确 false 就是不设置为不明确  

xh_pDialog.setIndeterminate(false);  

// 设置ProgressDialog 是否可以按退回键取消  

xh_pDialog.setCancelable(true);  

// 设置ProgressDialog 的一个Button  

xh_pDialog.setButton("确定", new Bt1DialogListener());  

// 让ProgressDialog显示  

xh_pDialog.show();  

 

 

 

重写dispatchKeyEvent方法 按返回键back 执行两次的解决方法

@Override

public boolean dispatchKeyEvent(KeyEvent event) {

  if(event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() != KeyEvent.ACTION_UP) {//不响应按键抬起时的动作 

   //TODO 代码  

    System.out.println("Back pressed. event.getKeyCode() => " + event.getKeyCode() + ", event.getKeyCode() => " + event.getAction());

            return true;//注意这儿返回值为true时该事件将不会继续往下传递,false时反之。根据程序的需要调整

  }

  return super.dispatchKeyEvent(event);

 }

 

当我们重写了onKeyDown方法后,如果return false,则会继续调用系统的onKeyDown方法。

如果只想让程序调用自己写的onKeyDown,则需要return true。

利用该特性可以拦截耳机耳机按键,防止启动音乐。

0 0
原创粉丝点击