`
chenlong_1988
  • 浏览: 183438 次
  • 性别: Icon_minigender_2
社区版块
存档分类

Android中的HTTP通信

阅读更多

Android中的HTTP通信

 

转:http://blog.sina.com.cn/s/blog_6e13876401013hpm.html

(2012-09-08 10:34:09)


自己整理,整理得不好,不喜勿喷!

HTTP通信

HttpURLConnection接口

HTTP超文本传输协议,用于传送WWW方式的数据。HTTP协议采用了请求/响应模式。

Android提供了HTTPURLConnection和HttpClient接口来开发HTTP程序。

HTTP使用最多的就是Get和Post,Get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给服务器。HttpUrlConnection是抽象类,无法直接实例化对象,所以只能够通过URL的openConnection方法获得。

URL url = new URL(“http://www.google.com/”);

HttpURLConnection urlconn = (HttpURlConnection)url.openConneciton();

openConnection只是创建了实例但并没真正的连接操作。

//设置输入(输出)流

urlconn.setDoOutput(true);

urlconn.setDoInput(true);

//设置方式POST

urlconn.setRequestMethod(“POST”);

//POST请求不能使用缓存

urlconn.setUseCaches(false);

//完成连接之后要关闭这个连接

urlconn.disconnect;

 

一般代码

String httpUrl = “http://www.baidu.com”;

String resultData = null;

URL url = null;

try{

         url = new URL(http);

}catch(MalformedException){

 

}

If(url!=null){

         Try{ 

                            //使用HTTPURLConnetion打开连接

                            HttpURLConnetion urlConn = (HttpURLConnetion)url.openConnetion();

                            //得到读取的类容

                            InputStreamReader in = new InputStreamReader(urlconn.getInputStream());

                            BufferReader buffer = new BufferReader(in);

                            String inputLine = null;

                            While((inputLine = buffer.readLine())!=null){

                                     resultData += inputLine;

}

//关闭InputStreamReader

In.close();

//关闭http连接

Urlconn.disconnect();

}

}

用Get方式传递参数很简单,只需加上传递的参数即可。

String httpurl1 = “http://www.baidu.com ?par=abcdefg ”;

?par=abcdefg为传递的参数par

 

由于HttpURLConnection默认使用Get方式,如果我们要像使用Post方式,则只需要setRequestMethod设置

 

主要代码:

//设置POST请求方式

urlconn.setRequestMethod(“POST”);

 

HttpClient接口

HttpClient更适合Android上开发互联网应用。

ClientConnectionManager 接口

ClientConnectionManager是客户端连接管理器接口,主要有以下几个抽象方法。

closeIdleConnections 关闭空闲的连接

releaseConnection 释放一个连接

requestConnection 请求一个新的连接

shutdown 关闭管理器并释放

 

DefaultHttpClient

DefaultHttpClient是默认的一个Http客户端,我们可以使用它创建一个Http连接

代码:

HttpClient httpclient = new DefaultHttpClient();

 

HttpResponse

HttpRespone是一个Http连接响应,当执行一个HTTP连接后,就会 返回一个HttpResponse,可以通过HttpResponse获得一些响应的信息。

请求一个Http连接并获得该请求是否成功的代码:

HttpResponse httpResponse = httpClient.execute(httpRequest());

If(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){

                   //连接成功

}

HttpClient中如何使用Get方式获取数据。这里需要使用HttpGet来构建一个Get方式的Http请求,然后通过HttpClient来执 行这个请求,HttpResponse在接收这个请求后给出响应,最后通过 “HttpResponse.getStatusLine().getStatusCode()”来判断请求是否成功并处理。

主要代码:

//http地址

String httpUrl = “http://192.168.0.1:8080/http1.jsp?par=Http Client_android_Get”;

//HttpGet连接对象

HttpGet httpRequest = new HttpGet(httpUrl);

try{

         //获取HttpCilent对象

HttpClient httpClient = new DefaultHttpClient();

//请求HttpClient,取得HttpReponse

HttpResponse httpResponse = httpCilent.execute(httpRequest);

//判断请求

If(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){

         String strResult = EntityUtil.toString(httpResponse.getEntity());

}

}catch(ClientProtocolException){}

catch(IOException){}

 

用POST方式与Get方式不一样

需要使用NameValuePair来保存传递的数据的参数,这里可以使用BasicNameValuePair来构造要被传递的参数,然后通过add方法添加到这个参数到NameValuePair中

代码:

//使用NameValuePair来保存要传递的Post参数

List params = new ArrayList();

//添加要传递的参数

Params.add(new BasicNamePair(“par”,”HttpClient_android_Post”));

Post方式需要设置所使用的字符集,最后就和Get方式一样通过HttpClient来请求这个连接,返回响应并处理。

 

关键代码:

//HttpPost连接对象

HttpPost httpRequest = new HttpPost(httpUrl);

List params = new ArrayList();

//添加要传递的参数

Params.add(new BasicNamePair(“par”,”HttpClient_android_Post”));

try{

         //设置字符集

         HttpEntity httpentity = new UrlEncodedFormEntity(params,”gb2312”);

         //请求httpRequest

         httpRequest.setEntity(httpentity);

         //…………..和Get操作一样

}

 

实时更新:

实时更新需要通过一个线程来控制是视图的更新。

例:实现android程序中每隔5秒刷新一次视图。

public class Test_GetOnTimeActivity extends Activity {

         TextView tv ;

         Button btn;

         MyHandler myHandler;

         MyThread myThread;

 

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        tv = (TextView)findViewById(R.id.textView1);

        btn = (Button)findViewById(R.id.button1);

        btn.setOnClickListener(new Button.OnClickListener(){

 

                            @Override

                            public void onClick(View v) {

                                     refresh();

                            }

 

        });

        myHandler = new MyHandler();

        myThread = new MyThread();

        new Thread(myThread).start();

    }

 

    //刷新网页更新

    private void refresh(){

             String httpUrl = "http://www.sina.com.cn/";

             String resultData = null;

             URL url = null;

             try{

                       url = new URL(httpUrl);

             }catch(MalformedURLException e){

                       e.printStackTrace();

             }

             if(url!=null){

                       try{

                                HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();

                                InputStreamReader in = new InputStreamReader(urlConn.getInputStream());

                                BufferedReader buffer = new BufferedReader(in);

                                String inputLine = null;

                                while((inputLine = buffer.readLine())!=null){

                                         resultData += inputLine+"\n";

                                }

                                in.close();

                                urlConn.disconnect();

                       }catch(IOException e){

                                e.printStackTrace();

                       }

                       if(resultData!=null){

                                tv.setText(resultData);

                                }else{

                                         tv.setText("No data");

                                }

             }

    }

 

    class MyThread implements Runnable{

 

                   @Override

                   public void run() {

                            while(true){

                                     try{

                                               Thread.sleep(5*1000);

                                               myHandler.sendMessage(myHandler.obtainMessage());

                                     }catch(InterruptedException e){

                                               e.printStackTrace();

                                     }

                            }

                   }

    }

 

    class MyHandler extends Handler{

 

                   @Override

                   public void handleMessage(Message msg) {

                            super.handleMessage(msg);

                            refresh();

                   }

 

                   public MyHandler() {

                            super();

                   }

 

    }

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics