代码改变世界

Android HttpURLConnection 与 HttpClient

2013-02-18 17:09  waddell  阅读(372)  评论(0编辑  收藏  举报
package com.example.phonedemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
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;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.phonedemo.util.Utils;

public class HttpDemo extends Activity {

    private static final String PATH = "http://192.168.1.121:8080/wwwroot/android/login.jsp";
    private static final String NAME = "qinxijuan";
    private static final String PASSWORD = "123456";

    private Button getConnBut = null;
    private Button postConnBut = null;
    private Button getClientBut = null;
    private Button postClientBut = null;
    private TextView text = null;
    private LinearLayout layout = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        this.layout = new LinearLayout(this);
        this.layout.setOrientation(LinearLayout.VERTICAL);

        this.getConnBut = new Button(this);
        this.getConnBut.setText("HttpURLConnection GET请求");
        this.getConnBut.setOnClickListener(new ConnGet());
        this.layout.addView(this.getConnBut, Utils.wrap_v);

        this.postConnBut = new Button(this);
        this.postConnBut.setText("HttpURLConnection post请求");
        this.postConnBut.setOnClickListener(new ConnPost());
        this.layout.addView(this.postConnBut, Utils.wrap_v);

        this.getClientBut = new Button(this);
        this.getClientBut.setText("HttpClient post请求");
        this.getClientBut.setOnClickListener(new ClientGet());
        this.layout.addView(this.getClientBut, Utils.wrap_v);

        this.postClientBut = new Button(this);
        this.postClientBut.setText("HttpClient post请求");
        this.postClientBut.setOnClickListener(new ClientPost());
        this.layout.addView(this.postClientBut, Utils.wrap_v);

        this.text = new TextView(this);
        this.text.setText("等待取得链接");
        this.layout.addView(this.text, Utils.wrap_h);

        super.addContentView(layout, Utils.match);

    }

    class ConnGet implements OnClickListener {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String path = PATH + "?" + "name=" + NAME + "&password=" + PASSWORD;
            URL url = null;
            HttpURLConnection conn = null;
            BufferedReader bfr = null;
            StringBuffer result = new StringBuffer();
            try {
                url = new URL(path);
                conn = (HttpURLConnection) url.openConnection();
                bfr = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String input;
                while ((input = bfr.readLine()) != null) {
                    result.append(input);
                }
                conn.disconnect();
                System.out.println("result: " + result.toString());
                if (Boolean.parseBoolean(result.toString().trim())) {
                    HttpDemo.this.text
                            .setText("HttpURLConnection get方式已经成功获取数据。");
                } else {
                    HttpDemo.this.text.setText("HttpURLConnection get方式获取数据失败");
                }
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    class ConnPost implements OnClickListener {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            URL url = null;
            HttpURLConnection conn = null;
            BufferedReader bfr = null;
            StringBuffer result = new StringBuffer();
            try {
                url = new URL(HttpDemo.this.PATH);
                conn = (HttpURLConnection) url.openConnection();
                // HttpURLConnection 默认是get请求方式,所以要设置成 true
                conn.setRequestMethod("POST");
                // 设置需要输入参数
                conn.setDoOutput(true);
                String params = "name=" + NAME + "&password=" + PASSWORD;
                // 设置参数
                conn.getOutputStream().write(params.getBytes());
                // 读取返回流
                bfr = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String input = null;
                while ((input = bfr.readLine()) != null) {
                    result.append(input);
                }
                if (Boolean.parseBoolean(result.toString().trim())) {
                    HttpDemo.this.text
                            .setText("HttpURLConnection Post方式已经成功获取数据。");
                } else {
                    HttpDemo.this.text
                            .setText("HttpURLConnection post方式获取数据失败");
                }
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    class ClientGet implements OnClickListener {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String path = PATH + "?" + "name=" + NAME + "&password=" + PASSWORD;
            HttpGet request = new HttpGet(path);
            HttpClient httpClient = new DefaultHttpClient();
            HttpResponse response = null;
            String result = null;
            try {
                response = httpClient.execute(request);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    result = EntityUtils.toString(response.getEntity());
                }
                if (Boolean.parseBoolean(result.trim())) {
                    HttpDemo.this.text.setText("HttpClient GET方式已经成功获取数据。");
                } else {
                    HttpDemo.this.text.setText("HttpClient GET方式获取数据失败");
                }
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    class ClientPost implements OnClickListener {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            HttpPost request = new HttpPost(PATH);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", NAME));
            params.add(new BasicNameValuePair("password", PASSWORD));
            String result = null;
            try {
                HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
                request.setEntity(entity);
                HttpClient client = new DefaultHttpClient();
                HttpResponse response = client.execute(request);
                if (response.getStatusLine().getStatusCode() == 200){
                    result = EntityUtils.toString(response.getEntity());
                }
                if (Boolean.parseBoolean(result.trim())){
                    HttpDemo.this.text.setText("HttpClient POST方式已经成功获取数据。");
                } else {
                    HttpDemo.this.text.setText("HttpClient POST方式获取数据失败");
                }
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}