Android使用HttpClient方法和易錯問題

來源:互聯網
上載者:User

標籤:android   blog   http   io   ar   os   使用   java   sp   

HttpClient為Android開發人員提供了跟簡潔的操作Http網路連接的方法,在串連過程中也有兩種方式,get和post,先看一下怎樣實現的

預設是get方式

//先將參數放入List,再對參數進行URL編碼  List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();  params.add(new BasicNameValuePair("param1", "中國"));  params.add(new BasicNameValuePair("param2", "value2"));  //baseUrl             String baseUrl = "http://www.baidu.com";    //將URL與參數拼接  HttpGet getMethod = new HttpGet(baseUrl + "?" + param);                HttpClient httpClient = new DefaultHttpClient();    try {      HttpResponse response = httpClient.execute(getMethod); //發起GET請求        Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //擷取響應碼      Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"));//擷取server響應內容  } catch (ClientProtocolException e) {      // TODO Auto-generated catch block      e.printStackTrace();  } catch (IOException e) {      // TODO Auto-generated catch block      e.printStackTrace();  }  


post方式

//和GET方式一樣,先將參數放入List  params = new LinkedList<BasicNameValuePair>();  params.add(new BasicNameValuePair("param1", "Post方法"));  params.add(new BasicNameValuePair("param2", "第二個參數"));                try {      HttpPost postMethod = new HttpPost(baseUrl);      postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //將參數填入POST Entity中                        HttpResponse response = httpClient.execute(postMethod); //運行POST方法      Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //擷取響應碼      Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //擷取響應內容                    } 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();  }  
假設須要在獲得網路資源後,去更新UI的一些東西,須要使用非同步方式,否則會錯誤發生

Handler handler = new Handler() {        @Override        public void handleMessage(Message msg) {            if (msg.what == 0x123) {                tv.setText(result);            }        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        tv = (TextView) findViewById(R.id.tv);        result = "";        final HttpClient httpclient = new DefaultHttpClient();        new Thread() {            public void run() {                HttpGet httpRequest = new HttpGet(                        "http://www.baidu.com");                try {                    HttpResponse httpResponse = httpclient.execute(httpRequest);                    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {                        // 取得返回的字串                        result = EntityUtils.toString(httpResponse.getEntity());                                              //tv.setText(result);//假設在這裡來使用會報錯                      Message msg = new Message();                       msg.what = 0x123;                       handler.sendMessage(msg);                    }                } catch (ClientProtocolException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }.start();        }




Android使用HttpClient方法和易錯問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.