Android 通過get和post方法訪問網路

來源:互聯網
上載者:User

      此demo示範android通過get和post要求方法同伺服器互動,因此需要搭建一個伺服器測試,可以使用Tomcat,具體方法參考:http://blog.csdn.net/youmingyu/article/details/52524006  ,demo:下載地址 。

      注意開啟訪問網路許可權:<uses-permission android:name="android.permission.INTERNET" />


源碼:

package fk.androiddemo_007;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLEncoder;//在Manifest檔案中註冊<uses-permission android:name="android.permission.INTERNET" />public class MainActivity extends AppCompatActivity implements View.OnClickListener {    EditText userText,passwordText,ipText;    TextView resText;    Button postBut,getBut;    String name,password,ip;    MyHandler handler;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        userText=(EditText)findViewById(R.id.userText);        passwordText=(EditText)findViewById(R.id.passwordText);        ipText=(EditText)findViewById(R.id.ipText);        resText=(TextView)findViewById(R.id.resText);        getBut=(Button)findViewById(R.id.getBut);        getBut.setOnClickListener(this);        postBut=(Button)findViewById(R.id.postBut);        postBut.setOnClickListener(this);        handler=new MyHandler();    }    @Override    public void onClick(View v) {        name=userText.getText().toString().trim();        password=passwordText.getText().toString().trim();        ip=ipText.getText().toString().trim();        if(v==getBut)            new GetThread().start();//用get方法發送        else new PostThread().start();//用post方法發送    }    //網路線程,因為不能在主線程訪問Intent    class GetThread extends Thread{        public void run(){            HttpURLConnection conn=null;//聲明連線物件            String urlStr="http://"+ip+":8080/example001.jsp?name="+name+"&password="+password;            InputStream is = null;            String resultData = "";            try {                URL url = new URL(urlStr); //URL對象                conn = (HttpURLConnection)url.openConnection(); //使用URL開啟一個連結,下面設定這個串連                conn.setRequestMethod("GET"); //使用get請求                if(conn.getResponseCode()==200){//返回200表示串連成功                    is = conn.getInputStream(); //擷取輸入資料流                    InputStreamReader isr = new InputStreamReader(is);                    BufferedReader bufferReader = new BufferedReader(isr);                    String inputLine  = "";                    while((inputLine = bufferReader.readLine()) != null){                        resultData += inputLine + "\n";                    }                    System.out.println("get方法取回內容:"+resultData);                    showRes("get方法取回內容:" + resultData);                }            } catch (IOException e) {                e.printStackTrace();            }        }    }    class PostThread extends Thread{        public void run(){            HttpURLConnection conn=null;            String urlStr="http://"+ip+":8080/example001.jsp";            InputStream is = null;            String resultData = "";            try {                URL url = new URL(urlStr); //URL對象                conn = (HttpURLConnection)url.openConnection(); //使用URL開啟一個連結,下面設定這個串連                conn.setRequestMethod("POST"); //使用POST請求                //參數字串                String param="name="+URLEncoder.encode(name,"UTF-8")//伺服器不識別漢字                    +"&password="+URLEncoder.encode(password,"UTF-8");                //用輸出資料流向伺服器發出參數,要求字元,所以不能直接用getOutputStream                DataOutputStream dos=new DataOutputStream(conn.getOutputStream());                dos.writeBytes(param);                dos.flush();                dos.close();                if(conn.getResponseCode()==200) {//返回200表示相應成功                    is = conn.getInputStream();   //擷取輸入資料流                    InputStreamReader isr = new InputStreamReader(is);                    BufferedReader bufferReader = new BufferedReader(isr);                    String inputLine = "";                    while ((inputLine = bufferReader.readLine()) != null) {                        resultData += inputLine + "\n";                    }                    System.out.println("post方法取回內容:" + resultData);                    showRes("post方法取回內容:" + resultData);                }            } catch (IOException e) {                e.printStackTrace();            }        }    }    //用於主線程發送訊息    public void showRes(String res){        Bundle bundle=new Bundle();        bundle.putString("res",res);//bundle中也可以放序列化或包裹化的類對象資料        Message msg=handler.obtainMessage();//每發送一次都要重新擷取        msg.setData(bundle);        handler.sendMessage(msg);//用handler向主線程發送資訊    }    //自訂handler類    class MyHandler extends Handler {        @Override        //接收別的線程的資訊並處理        public void handleMessage(Message msg) {            Bundle bundle=msg.getData();            resText.setText(bundle.get("res").toString());        }    }}

運行截圖:注意,方框內填寫自己的伺服器的IP地址



PS1:

Android同伺服器互動也可以使用HttpClient,但是在android 6.0(API 23)及以後中,Google已經移除了移除了Apache HttpClient相關的類,所以如果要繼續使用需要Apache HttpClient,需要添加相應的jar包,方法參考:http://blog.csdn.net/youmingyu/article/details/52526997

httpclient-4.5.2.jar :下載地址 ,官網下載地址:地址


PS2:

get方法與post方法的區別,截了一張Mars老師的圖:



相關文章

聯繫我們

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