HttpClient的post請求

手機歸屬地(整個代碼)

package com.example.day5_httpclient;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.message.BasicNameValuePair;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private EditText ed_phnum;
    private TextView tv_show;
Handler handler=new Handler(){
    public void handleMessage(android.os.Message msg) {
         switch (msg.what) {
        case 1:
            String ccontent=(String) msg.obj;
            tv_show.setText(ccontent);
            break;
        case 2:
            Toast.makeText(MainActivity.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
            break;
        case 3:
            Toast.makeText(MainActivity.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
            break;
        case 4:
            Toast.makeText(MainActivity.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
            break;
        case 5:
            Toast.makeText(MainActivity.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
            break;
        default:
            break;
        }
    };
};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ed_phnum = (EditText) findViewById(R.id.editText1);
        tv_show=(TextView)findViewById(R.id.textView1);
    }

    // http://life.tenpay.com/cgi-bin/mobile/MobileQueryAttribution.cgi?chgmobile=15850781443

    /**注意:1.請求網絡的耗時操作在子線程進行;
     * 2.訪問網絡要加權限:permission INTERNET
     * 3.只有主線程能更改UI,Toast也屬於更改UI
     * 4.注意參數名不能寫錯(chgmobile,否則能請求到數據,但是ERROR數據不全.得不到)
     * 5.toString("gb2312");類型與網上請求到的要一致
     */
    public void httpclientandhttppost(View v) {
        new Thread() {
            public void run() {
                try {
                    //創建HttpClient對象(---DefaultHttpClient是HttpClient接口的實現類)
                    HttpClient httpClient=new DefaultHttpClient();
                    //網址
                    String path = "http://life.tenpay.com/cgi-bin/mobile/MobileQueryAttribution.cgi";
                    //創建HttpPost對象並設置網址
                    HttpPost httpPost = new HttpPost(path);
                    //創建鍵值對類型的list集合(參數)
                    List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
                    //添加參數信息
                    parameters.add(new BasicNameValuePair("chgmobile", ed_phnum
                            .getText().toString().trim()));
                    //創建實體內容對象
                    HttpEntity entity = new UrlEncodedFormEntity(parameters,
                            "utf-8");
                    //設置請求的實體內容
                    httpPost.setEntity(entity);
                     //執行post請求
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    //從狀態行中獲取狀態碼
                    int statusCode = httpResponse.getStatusLine().getStatusCode();
                    //判斷狀態碼 成功
                    if(statusCode==200){
                        //獲取請求的內容
                        InputStream inputStream = httpResponse.getEntity().getContent();
                        ByteArrayOutputStream bytearrayoutputstream=new ByteArrayOutputStream();
                        byte[] b=new byte[1024];
                        int len;
                        while((len=inputStream.read(b))!=-1){
                            bytearrayoutputstream.write(b, 0, len);
                        }
                        String content = bytearrayoutputstream.toString("gb2312");
                        System.out.println("請求到的內容"+content);
                        handler.obtainMessage(1, content).sendToTarget();
                        //handler.sendMessage(Message.obtain(handler, 1, content));
                    }else{
                        //請求失敗
                        System.out.println("請求失敗");
                        handler.sendMessage(Message.obtain(handler, 2, "請求數據失敗"));
                    }
                } catch (UnsupportedEncodingException e) {
                    handler.sendMessage(Message.obtain(handler, 3, "UnsupportedEncodingException"));
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    handler.sendMessage(Message.obtain(handler, 4, "ClientProtocolException"));
                    e.printStackTrace();
                } catch (IOException e) {
                    handler.sendMessage(Message.obtain(handler, 5, "IOException"));
                    e.printStackTrace();
                }
            };
        }.start();
    }

}
發佈了41 篇原創文章 · 獲贊 1 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章