HttpUrlConnection与HttpClient的post、get的请求网络数据的方法

来源:互联网 发布:绿标域名认证生成器 编辑:程序博客网 时间:2024/06/03 16:00
package com.example.twentyfivecode;import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URI;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.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.content.Entity;import android.net.Uri;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.widget.Button;import android.widget.TextView;/** * @author HD * @date 2015-12-6 * @package_name com.example.twentyfivecode * @file_name MainActivity.java */public class MainActivity extends Activity {//  用HttpURLConnection的GET方法发送请求    private Button btnHttpURLGetRequest;//  用HttpURLConnection的POST方法发送请求    private Button btnHttpURLPostRequest;//  用HttpClient的Post方法发送请求    private Button btnPostRequest;//  用HttpClient的GET方法发送请求    private Button btnGetRequest;//  用来显示响应的文本    private TextView tvResponse;    public static final int SHOW_RESPONSE = 0;    Handler handler = new Handler() {        public void handleMessage(Message msg) {            switch (msg.what) {            case SHOW_RESPONSE:                String response = (String) msg.obj;                tvResponse.setText(response);                break;            }        };    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        btnHttpURLGetRequest = (Button) findViewById(R.id.btnHttpURLGetRequest);        btnHttpURLPostRequest = (Button) findViewById(R.id.btnHttpURLPostRequest);        btnPostRequest = (Button) findViewById(R.id.btnPostRequest);        btnGetRequest = (Button) findViewById(R.id.btnGetRequest);        tvResponse = (TextView) findViewById(R.id.tvResponse);        btnGetRequest.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {//              用HttpClient的GET方法发送请求                sendRequestWithHttpClientWithGET();            }        });        btnHttpURLGetRequest.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {//              用HttpURLConnection的GET方法发送请求                sendRequestWithHttpURLGet();            }        });        btnPostRequest.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {//              用HttpClient的POST方法发送请求                sendRequestWithHttpClientPOST();            }        });        btnHttpURLPostRequest.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {//              用HttpURLConnection的POST方法发送请求                sendRequestWithHttpURLPost();            }        });    }    private void sendRequestWithHttpURLGet() {        new Thread(new Runnable() {            @Override            public void run() {                // TODO 自动生成的方法存根                try {                    URL url = new URL("http://wwww.baidu.com");                    HttpURLConnection conn = (HttpURLConnection) url                            .openConnection();                    conn.setConnectTimeout(8 * 1000);                    conn.setReadTimeout(8 * 1000);                    conn.setRequestMethod("GET");                    conn.connect();                    InputStream inputStream = conn.getInputStream();                    BufferedReader bufferedReader = new BufferedReader(                            new InputStreamReader(inputStream));                    String line = "";                    StringBuilder builder = new StringBuilder();                    while ((line = bufferedReader.readLine()) != null) {                        builder.append(line);                    }                    Message msg = new Message();                    msg.what = SHOW_RESPONSE;                    msg.obj = builder.toString();                    handler.sendMessage(msg);                } catch (MalformedURLException e) {                    // TODO 自动生成的 catch 块                    e.printStackTrace();                } catch (IOException e) {                    // TODO 自动生成的 catch 块                    e.printStackTrace();                }            }        }).start();    }    private void sendRequestWithHttpURLPost() {        new Thread(new Runnable() {            @Override            public void run() {                // TODO 自动生成的方法存根                try {                    URL url = new URL("http://www.baidu.com");                    HttpURLConnection conn = (HttpURLConnection) url                            .openConnection();                    conn.setReadTimeout(8 * 1000);                    conn.setConnectTimeout(8 * 1000);                    conn.setRequestMethod("POST");//                  获得向服务器发送数据的输出流                    DataOutputStream outputStream = new DataOutputStream(conn                            .getOutputStream());//                  向输出流中写提交的数据,必须是键值对,并且中间用&符号分隔                    outputStream                            .writeBytes("username = admin&password = 123456");                    InputStream inputStream = conn.getInputStream();                    BufferedReader bufferedReader = new BufferedReader(                            new InputStreamReader(inputStream));                    String line = "";                    StringBuilder builder = new StringBuilder();                    while ((line = bufferedReader.readLine()) != null) {                        builder.append(line);                    }                    Message msg = new Message();                    msg.what = SHOW_RESPONSE;                    msg.obj = builder.toString();                    handler.sendMessage(msg);                } catch (MalformedURLException e) {                    // TODO 自动生成的 catch 块                    e.printStackTrace();                } catch (IOException e) {                    // TODO 自动生成的 catch 块                    e.printStackTrace();                }            }        }).start();    }    private void sendRequestWithHttpClientWithGET() {        new Thread(new Runnable() {            @Override            public void run() {                // TODO 自动生成的方法存根                HttpClient client = new DefaultHttpClient();                HttpGet httpGet = new HttpGet("http://www.baidu.com");                try {//                  服务器响应的所有信息都在httpResponse中                    HttpResponse httpResponse = client.execute(httpGet);//                  取出信息中的状态码,如果等于200就说明请求和响应都成功了                    if (httpResponse.getStatusLine().getStatusCode() == 200) {//                      取出实例                        HttpEntity entity = httpResponse.getEntity();//                      用EntityUTils的静态方法把entity实例转换成字符串,为了避免产生乱码,指定用"utf-8"解码                        String response = EntityUtils.toString(entity, "utf-8");                        Message msg = new Message();                        msg.what = SHOW_RESPONSE;                        msg.obj = response;                        handler.sendMessage(msg);                    }                } catch (ClientProtocolException e) {                    // TODO 自动生成的 catch 块                    e.printStackTrace();                } catch (IOException e) {                    // TODO 自动生成的 catch 块                    e.printStackTrace();                }            }        }).start();    }    private void sendRequestWithHttpClientPOST() {        new Thread(new Runnable() {            @Override            public void run() {                // TODO 自动生成的方法存根                HttpClient client = new DefaultHttpClient();                HttpPost httpPost = new HttpPost("http://www.baidu.com");//              需要发送给服务器的数据集合,以NameValuePair的实例集合方法                List<NameValuePair> list = new ArrayList<NameValuePair>();                list.add(new BasicNameValuePair("username", "admin"));                list.add(new BasicNameValuePair("password", "123456"));                UrlEncodedFormEntity entity;                try {//                  把list转换成一个Entity实例                    entity = new UrlEncodedFormEntity(list, "utf-8");//                  把Entity放至HttpPost中                    httpPost.setEntity(entity);                    HttpResponse httpResponse = client.execute(httpPost);                    if (httpResponse.getStatusLine().getStatusCode() == 200) {                        HttpEntity httpEntity = httpResponse.getEntity();                        String response = EntityUtils.toString(httpEntity,                                "UTF-8");                        Message msg = new Message();                        msg.what = SHOW_RESPONSE;                        msg.obj = response;                        handler.sendMessage(msg);                    }                } catch (UnsupportedEncodingException e) {                    // TODO 自动生成的 catch 块                    e.printStackTrace();                } catch (ClientProtocolException e) {                    // TODO 自动生成的 catch 块                    e.printStackTrace();                } catch (IOException e) {                    // TODO 自动生成的 catch 块                    e.printStackTrace();                }            }        }).start();    }}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"     >    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal" >        <Button        android:id="@+id/btnGetRequest"        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_weight="1"        android:text="HttpClient的GET方法请求" />      <Button        android:id="@+id/btnPostRequest"        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_weight="1"        android:text="HttpClient的POST方法请求" />       <Button        android:id="@+id/btnHttpURLGetRequest"        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_weight="1"        android:text="HttpURLcon的GET方法请求" />        <Button        android:id="@+id/btnHttpURLPostRequest"        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_weight="1"        android:text="HttpURLcon的POST方法请求" />    </LinearLayout>    <ScrollView        android:layout_width="match_parent"        android:layout_height="match_parent" >        <TextView            android:id="@+id/tvResponse"            android:layout_width="match_parent"            android:layout_height="match_parent" />    </ScrollView></LinearLayout>
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.twentyfivecode"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="14"        android:targetSdkVersion="21" />    <uses-permission android:name="android.permission.INTERNET"/>    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name=".MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>
0 0