android通訊HttpClient,androidhttpclient

來源:互聯網
上載者:User

android通訊HttpClient,androidhttpclient

下面為使用HttpClient的一個登入伺服器的小例子

package com.liang.logindemo;import android.os.Bundle;import android.support.v7.app.ActionBarActivity;import android.view.View;import android.widget.EditText;import android.widget.Toast;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;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.entity.BufferedHttpEntity;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.Reader;import java.io.StringReader;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLEncoder;import java.util.ArrayList;import java.util.List;public class MainActivity3 extends ActionBarActivity {    private EditText et_userName;    private EditText et_password;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        et_userName= (EditText) findViewById(R.id.et_userName);        et_password= (EditText) findViewById(R.id.et_password);    }    public void login(View view) {        String str=et_userName.getText().toString();        try {            str=URLEncoder.encode(str,"utf-8");        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        }        final String userName=str;        final String password=et_password.getText().toString();        //在子線程中訪問網路        new Thread(new Runnable() {            @Override            public void run() {                try {                    final boolean isSuccess =loginByPost(userName,password);                    //final boolean isSuccess = loginByGet(userName,password);                    //使用此方法可不使用Handler通知主線程,方法內所做操作由主線程完成                    runOnUiThread(new Runnable() {                        @Override                        public void run() {                            if(isSuccess){                                Toast.makeText(MainActivity3.this,"成功了!!!",Toast.LENGTH_SHORT).show();                            }else{                                Toast.makeText(MainActivity3.this,"失敗了!!!",Toast.LENGTH_SHORT).show();                            }                        }                    });                } catch (Exception e) {                    e.printStackTrace();                }            }        }).start();    }    /**     * HttpClient通過GET請求方式訪問伺服器     * @param userName,password     * @return     * @throws Exception     */    private Boolean loginByGet(String userName,String password) throws Exception{        //伺服器位址        String url="http://192.168.1.140:8080/Login/servlet/Login";        String data="?userName="+userName + "&password="+password;        HttpClient client=null;        //定義一個用戶端        client = new DefaultHttpClient();        //定義一個get請求        HttpGet get = new HttpGet(url+data);        //執行get請求,獲得響應對象        HttpResponse response = client.execute(get);        //獲得響應狀態代碼        int code = response.getStatusLine().getStatusCode();        //返回結果        if(code==200) {            //獲得響應內容            InputStream is = response.getEntity().getContent();            BufferedReader reader = new BufferedReader(new InputStreamReader(is));            String text = reader.readLine();            reader.close();            is.close();            return "SUCCESS".equals(text) ? true : false;        }        if(client!=null){            //關閉串連            client.getConnectionManager().shutdown();        }        return false;    }    /**     *HttpClient通過POST請求方式訪問伺服器     * @param userName     * @param password     * @return     * @throws Exception     */    boolean loginByPost(String userName,String password) throws Exception{        //伺服器位址        String url="http://192.168.1.140:8080/Login/servlet/Login";        HttpClient client=null;        //定義一個用戶端        client = new DefaultHttpClient();        //定義一個Post請求        HttpPost post = new HttpPost(url);        //佈建要求資料        List<NameValuePair> list = new ArrayList<NameValuePair>();        list.add(new BasicNameValuePair("userName",userName));        list.add(new BasicNameValuePair("password",password));        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list);        post.setEntity(entity);        //執行get請求,獲得響應對象        HttpResponse response = client.execute(post);        //獲得響應狀態代碼        int code = response.getStatusLine().getStatusCode();        //返回結果        if(code==200) {            //獲得響應內容            InputStream is = response.getEntity().getContent();            BufferedReader reader = new BufferedReader(new InputStreamReader(is));            String text = reader.readLine();            reader.close();            is.close();            return "SUCCESS".equals(text) ? true : false;        }        if(client!=null){            //關閉串連            client.getConnectionManager().shutdown();        }        return false;    }}

需要資訊清單檔中添加網路存取權限


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.