Android 初識網絡之get/post方法演示

佈局:

<?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.administrator.jreduch08.HttpActivity">   
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="查詢(get方式)"
        android:id="@+id/search""/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="查詢(post方式)"
        android:id="@+id/search1"
        android:layout_below="@+id/search"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:text="查詢結果"
        android:id="@+id/show"
        android:layout_below="@+id/search1"/>   
</RelativeLayout>

佈局效果展示:


代碼:


package com.example.administrator.jreduch08;

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 {
    private Button search;
    private TextView show;
    private Button search1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http);
        search= (Button) findViewById(R.id.search);
        search1= (Button) findViewById(R.id.search1);
        show= (TextView) findViewById(R.id.show);
        //get請求監聽
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url="http://192.168.42.23:8080/" +
                        "HttpTest/index.jsp?option=getUser&uName=jerehedu";
                new MyGet().execute(url);
            }
        });
        //post請求監聽
        search1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] arg=new String[2];
                arg[0]="http://192.168.42.23:8080/" +
                        "HttpTest/index.jsp?option=getUser&uName=jerehedu";
                arg[1]="option=getUser&uName=jerehedu";
            new MyPost().execute(arg);
            }
        });
    }
    public class MyPost extends AsyncTask<String,Void,String>{

        @Override
        protected String doInBackground(String... params) {
            StringBuilder sbd=new StringBuilder();
            HttpURLConnection con=null;
            InputStream is=null;
            try {
                URL url=new URL(params[0]);
                con= (HttpURLConnection) url.openConnection();
                con.setConnectTimeout(5 * 1000);
                con.setReadTimeout(5 * 1000);
                con.setRequestMethod("POST");
                con.setDoInput(true);
                con.setDoInput(true);
                con.setUseCaches(false);
                con.setRequestProperty("Charset", "UTF-8");
                con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
                //strings應該是這樣的樣式 option=getUser&uName=jerehedu
                String strings=params[1];
                OutputStream os=con.getOutputStream();
                os.write(strings.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方法接收
    */
    public class MyGet extends AsyncTask<String,Void,String>{

       //在onPreExecute在主線程中執行命令,通常用於進度條的初始化
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        // doInBackground 在子線程中執行命令
        @Override
        protected String doInBackground(String... params) {
            HttpURLConnection con=null;
            InputStream is=null;
            StringBuilder sbd=new StringBuilder();
            try {
                URL url=new URL(params[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);
        }
    }
}
效果展示:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章