Android——網路 GET請求+POST請求

來源:互聯網
上載者:User

標籤:

Android——網路  GET請求+POST請求


擷取資料用GET請求   ??

增刪改查修改資料用POST請求




package com.example.jreduch07;import android.os.AsyncTask;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;public class HttpActivity extends AppCompatActivity {public EditText  et;    private Button search;    private Button search1;    private TextView show;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_http);        et=(EditText)findViewById(R.id.et);        search=(Button)findViewById(R.id.search);        search1=(Button)findViewById(R.id.search1);        show=(TextView)findViewById(R.id.show);        search.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                String url="http://192.168.1.48:8080/HttpTest/index.jsp?option=getUser&uName=jerehedu";                new  MyGetJob().execute(url);            }        });        search1.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                String[] arg=new String[2];                arg[0]="http://192.168.1.48:8080/HttpTest/index.jsp";                arg[1]="option=getUser&uName=jerehedu";                new MyPostJob1().execute(arg);            }        });    }    private  class MyPostJob1 extends AsyncTask<String,Void,String>{    @Override    protected String doInBackground(String... strings) {        HttpURLConnection con=null;        InputStream is=null;        StringBuilder sbd=new StringBuilder();        try {            URL url=new URL(strings[0]);            con= (HttpURLConnection) url.openConnection();            con.setConnectTimeout(5*1000);            con.setReadTimeout(5*1000);            con.setRequestMethod("POST");            con.setDoInput(true);            con.setDoOutput(true);            con.setUseCaches(false);            con.setRequestProperty("Charset","UTF-8");            con.setRequestProperty("Content-type","application/x-www-form-urlencoded");//            con.setRequestProperty("Charset","UTF-8");//            con.setRequestProperty("Content-type","application/x-www-from-urlencoded");            //params應該是這樣的=》option=getUser&uName=jerehedu            String params=strings[1];            OutputStream os=con.getOutputStream();   //資料轉送  流            os.write(params.getBytes());            os.flush();            os.close();            if (con.getResponseCode()==200) {              is=con.getInputStream();                int next = 0;                byte[] b = new byte[1024];                while ((next = is.read(b)) > 0) {                    sbd.append(new String(b, 0, next));                }            }        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }finally {            if (is!=null){                try {                    is.close();                } catch (IOException e) {                    e.printStackTrace();                }                if (con!=null){                    con.disconnect();  //中斷連線                }            }        }        return sbd.toString();    }    @Override    protected void onPostExecute(String s) {        super.onPostExecute(s);        show.setText("POST請求結果:"+s);    }}    /*    AsyncTask非同步任務類    非同步任務類的第一個參數會傳到doInBackground方法中    第三個參數              #指定doINBackground方法的傳回值              #doINBackground方法的傳回值會被OnPostExecute接收     */        private class MyGetJob extends AsyncTask<String, Void, String> {            //onPreExecute在主線程中執行命令            //進度條的初始化            @Override            protected void onPreExecute() {                super.onPreExecute();            }            //doInBackground在子線程中執行名命令            @Override            protected String doInBackground(String... strings) {                HttpURLConnection con = null;                InputStream is = null;                StringBuilder sbd = new StringBuilder();                try {                    URL url = new URL(strings[0]);                    con = (HttpURLConnection) url.openConnection();                    con.setConnectTimeout(5 * 1000);                    con.setReadTimeout(5 * 1000);                /*                *http相應200:成功                * 404未找到                * 500發生錯誤                 */                    if (con.getResponseCode() == 200) {                        is = con.getInputStream();                        int next = 0;                        byte[] bt = new byte[1024];                        while ((next = is.read(bt)) > 0) {                            sbd.append(new String(bt, 0, next));                        }                    }                } catch (MalformedURLException e) {                    e.printStackTrace();                } catch (IOException e) {                    e.printStackTrace();                } finally {                    if (is != null) {                        try {                            is.close();                        } catch (IOException e) {                            e.printStackTrace();                        }                        if (con != null) {                            con.disconnect();  //中斷連線                        }                    }                }                return sbd.toString();            }            //onPostExecute在UI線程中執行命令  主線程            @Override            protected void onPostExecute(String s) {                super.onPostExecute(s);                show.setText(s);            }        }    }
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.example.jreduch07.HttpActivity">    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="姓名!"        android:textSize="20dp"        android:layout_alignTop="@+id/et"        android:layout_alignParentStart="true"        android:layout_alignBottom="@+id/et"        android:id="@+id/textView" />    <EditText        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:hint="請輸入要尋找姓名"        android:id="@+id/et"        android:layout_alignBottom="@+id/search"        android:layout_centerHorizontal="true" />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="查詢(GET方法)"        android:id="@+id/search"        android:layout_alignParentTop="true"        android:layout_alignParentEnd="true" />    <TextView        android:layout_width="match_parent"        android:layout_height="150dp"        android:background="#fff30d"        android:id="@+id/show"        android:textSize="30sp"        android:text="查詢結果:"        android:layout_below="@+id/search1"        android:layout_alignParentStart="true" />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="查詢(post方法)"        android:id="@+id/search1"        android:layout_below="@+id/et"        android:layout_alignParentEnd="true" /></RelativeLayout>









Android——網路 GET請求+POST請求

聯繫我們

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