1. 程式人生 > >Http的get和post請求簡單應用

Http的get和post請求簡單應用

網路請求中需要遵循http協議,而http有許多方法,大家一般最常用的就是post和get請求方法了!
其中,post和get都可以向伺服器傳送和請求資料,而我們一般都習慣用get請求資料,post傳送資料!get方法是把資料拼接到請求行裡面,我們可以直接看到裡面的資料,相比較post不安全,但是簡單,快捷(大小限制不超過2K)!post則是把要傳送的資料轉換成流的方式,大小不限制,上傳給伺服器,相比較get安全些!

基礎定義和知識講解不詳細,大家可以參考大神的講解,詳細學習:

連結地址

其中本人AS版本2.3.如果你的AS版本低於2.2估計執行我的程式碼會報錯,因為用到了最新的ConstraintLayout書寫的佈局,學習ConstraintLayout的連結我也放上去:

效果圖上兩張:
這裡寫圖片描述

這裡寫圖片描述
下面我們直接上程式碼:
Xml佈局程式碼就不放了都是用滑鼠拉過來拉過去自動生成的程式碼

MainActivity程式碼:

package com.btzh.myhttptest;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import
android.widget.TextView; import CommonUntils.HttpUntils; public class MainActivity extends BaseActivity implements View.OnClickListener { private Button htmlbtn, picbtn,posthtmlbtn,postpichtn; private TextView textView; private ImageView imageView; int viewID = -1; HttpUntils Myuntils = new
HttpUntils(); String XML_Url = "http://toutiao.sogou.com/?fr=qqxwtt"; String XMl_Url_test = "http://baike.sogou.com/v6234.htm?fromTitle=%E7%99%BE%E5%BA%A6"; String pic_Url = "http://d.ifengimg.com/mw978_mh598/p2.ifengimg.com/a/2017_15/65bdb6e5ca68409_size79_w930_h620.jpg"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); initViews(); } /** * 初始化檢視控制元件 */ private void initViews(){ htmlbtn = (Button) findViewById(R.id.button_gethtml); htmlbtn.setOnClickListener(this); picbtn = (Button) findViewById(R.id.button_getpic); picbtn.setOnClickListener(this); textView = (TextView)findViewById(R.id.textView); imageView = (ImageView)findViewById(R.id.imageView); posthtmlbtn = (Button)findViewById(R.id.button_posthtml); posthtmlbtn.setOnClickListener(this); postpichtn = (Button)findViewById(R.id.button_postpic); postpichtn.setOnClickListener(this); } @Override public void onClick(View v) { viewID = v.getId(); if (viewID == R.id.button_gethtml) { //get獲取XMl資訊 new MyXMlTask().execute(); }else if (viewID == R.id.button_getpic) { //get獲取圖片資訊 showProgressDialog("正在載入圖片!"); new MyAsyncTask().execute(); }else if (viewID == R.id.button_posthtml) { //post獲取xml資訊 new MyPostTask().execute(); }else if (viewID == R.id.button_postpic) { //post獲取圖片資訊 new MyPostpicTask().execute(); }else { } } /** * get方法獲取圖片資訊 */ private class MyAsyncTask extends AsyncTaskUntils<Object, Object, Object>{ @Override protected void onPostExecute(Object o) { super.onPostExecute(o); hideProgressDialog(); if (textView.getVisibility()==View.VISIBLE){ textView.setText(""); textView.setVisibility(View.GONE); } imageView.setVisibility(View.VISIBLE); imageView.setImageBitmap((Bitmap) o); } } /** * get 方法非同步獲取url資料 */ private class MyXMlTask extends AsyncTask<String, Integer,String>{ @Override protected void onPreExecute() { super.onPreExecute(); showProgressDialog(R.string.XMl_Toast); } @Override protected String doInBackground(String... params) { String string = Myuntils.URL_getString(XML_Url); return string; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); hideProgressDialog(); if (imageView.getVisibility()==View.VISIBLE){ imageView.setImageDrawable(null); imageView.setVisibility(View.GONE); } textView.setVisibility(View.VISIBLE); textView.setText(s); } } /** * Post 方法非同步獲取url資料 */ private class MyPostTask extends AsyncTask<String,Integer,String>{ @Override protected void onPreExecute() { super.onPreExecute(); showProgressDialog("Post正在載入網頁資訊!"); } @Override protected String doInBackground(String... params) { String postStr = Myuntils.URL_postString(XMl_Url_test); return postStr; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); hideProgressDialog(); if (imageView.getVisibility()==View.VISIBLE){ imageView.setImageDrawable(null); imageView.setVisibility(View.GONE); } textView.setVisibility(View.VISIBLE); textView.setText(s); } } /** * Post 方法非同步獲取url圖片資料 */ private class MyPostpicTask extends AsyncTask<String,Object,Object>{ @Override protected void onPreExecute() { super.onPreExecute(); showProgressDialog("Post正在載入圖片資訊..."); } @Override protected Object doInBackground(String... params) { Bitmap postbitmap = Myuntils.URL_postitmap(pic_Url); return postbitmap; } @Override protected void onPostExecute(Object o) { super.onPostExecute(o); hideProgressDialog(); if (textView.getVisibility()==View.VISIBLE){ textView.setText(""); textView.setVisibility(View.GONE); } imageView.setVisibility(View.VISIBLE); imageView.setImageBitmap((Bitmap)o); } } }

程式碼註釋很詳細,其中用的是asynctask非同步來處理的訊息,沒有用handler,以後會用!
然後就是自己封裝的http和流解析的兩個類了,

package CommonUntils;

import android.graphics.Bitmap;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import CommonUntils.StreamTools;

/**
 * Created by Lenovo on 2017/4/7.
 */

public class HttpUntils {
    private int HTTP_TIMEOUT_CONNECTION = 6*10000;
    private int HTTP_TIMER_READ = 1*10000;

    /**
     * 返回bitmap
     * @param httpUrl
     * @return
     */
    public Bitmap URL_getbitmap(String httpUrl)
    {
        Bitmap bitmap = null;
        if ("" == httpUrl||null==httpUrl){
            return null;
        }
        InputStream inputStream = null;
        try {
            //建立url物件
            URL url = new URL(httpUrl);
            //開啟connection連線
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            //設定請求方法
            connection.setRequestMethod("GET");
            //設定連線超時時間
            connection.setConnectTimeout(HTTP_TIMEOUT_CONNECTION);
            //設定讀取時間
            connection.setReadTimeout(HTTP_TIMER_READ);
            //connection連結
            connection.connect();
            //判斷是否連線成功,識別符號號為200
            if (HttpURLConnection.HTTP_OK!=connection.getResponseCode())
            {
                return null;
            }
            //獲取請求到的流
             inputStream = connection.getInputStream();
            //bitmap接收流物件(流轉換為Bitmap格式物件)
             bitmap = StreamTools.getBitmap(inputStream);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {  //一般最好寫上,用來關閉前面開啟的流物件,來減少記憶體佔用
            try {
                    if (null!=inputStream){
                        inputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

        }
        return bitmap;
    }

    public String URL_getString(String httpUrl)
    {
        String string = "";
        if ("" == httpUrl || null==httpUrl){
            return "值為空!";
        }
        InputStream inputStream = null;
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(HTTP_TIMEOUT_CONNECTION);
            connection.setReadTimeout(HTTP_TIMER_READ);
            connection.connect();
            if (HttpURLConnection.HTTP_OK!=connection.getResponseCode())
            {
                return "連線失敗!";
            }
            inputStream = connection.getInputStream();
            string = StreamTools.getString(inputStream);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (null!=inputStream){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return string;
    }

    /**
     * post 請求資料返回 String
     * @param httpUrl
     * @return String
     */
    public String URL_postString(String httpUrl)
    {
        if ("".equals(httpUrl) || null==httpUrl){
            return null;
        }
        OutputStream outputStream = null;
        String postStr = "";
        InputStream inputStream = null;
        try {
            //建立Url物件
            URL url = new URL(httpUrl);
            //建立connection的url連線
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setConnectTimeout(HTTP_TIMEOUT_CONNECTION);
            connection.setReadTimeout(HTTP_TIMER_READ);
            connection.setRequestMethod("POST");
            //這兩個方法post必須開啟
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.connect();
            //這句話加上一直報錯,說我已經connect成功伺服器,是不是需要寫在connection.connect();前面
//            connection.setUseCaches(false);
            //data為需要傳入伺服器的資料,這裡我們傳空
            String data = "";
            //開啟輸入流
            outputStream = connection.getOutputStream();
            //往輸入流中寫入我們需要傳入伺服器的資料(格式為byte格式)
            outputStream.write(data.getBytes());
            outputStream.flush();
            //判斷是否響應成功(其實就是Tcp/IP三次握手是否成功)
            if (HttpURLConnection.HTTP_OK!=connection.getResponseCode()){
                return "連線失敗";
            }
            //獲取伺服器返回資料流
            inputStream = connection.getInputStream();
            //轉換為String格式
            postStr = StreamTools.getString(inputStream);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {  //關閉各種流
                try {
                    if (outputStream!=null){
                        outputStream.close();
                    }
                    if (inputStream!=null){
                        inputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

        }
        return postStr;
    }

    /**
     * post 請求資料返回Bitmap
     * @param httpUrl
     * @return Bitmap
     */
    public Bitmap URL_postitmap(String httpUrl)
    {
        if ("".equals(httpUrl) || null==httpUrl){
            return null;
        }
        OutputStream outputStream = null;
        Bitmap postBitmap = null;
        InputStream inputStream = null;
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setConnectTimeout(HTTP_TIMEOUT_CONNECTION);
            connection.setReadTimeout(HTTP_TIMER_READ);
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.connect();
//            connection.setUseCaches(false);
            String data = "";
            outputStream = connection.getOutputStream();
            outputStream.write(data.getBytes());
            outputStream.flush();
            if (HttpURLConnection.HTTP_OK!=connection.getResponseCode()){
                return null;
            }
            inputStream = connection.getInputStream();
            postBitmap = StreamTools.getBitmap(inputStream);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (outputStream!=null){
                    outputStream.close();
                }
                if (inputStream!=null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return postBitmap;
    }
}

Stream類

package CommonUntils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by Lenovo on 2017/4/7.
 */

public class StreamTools {
    /**
     * inputStream 轉換 Bitmap;
     * @param inputStream
     * @return bitmap
     */
    public static Bitmap getBitmap(InputStream inputStream){

        if (null == inputStream){
            return null;
        }
        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
        return bitmap;
    }

    /**
     * inputStream轉String
     * @param inputStream
     * @return String
     */
    public static String getString(InputStream inputStream){
        if (null==inputStream){
            return null;
        }
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader reader = new BufferedReader(inputStreamReader);
        StringBuffer stringBuffer = new StringBuffer("UTF-8");
        String line = null;
        try {
            while ((line = reader.readLine())!=null){
                stringBuffer.append(line+"\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return stringBuffer.toString();
    }

    /**
     * inputStream 轉 byte[]
     * @param inputStream
     * @return byte[]
     */
    public static byte[] getBytes(InputStream inputStream) {
        String str = "";
        byte[] readByte = new byte[1024];
        int readCount = -1;
        try {
            while ((readCount = inputStream.read(readByte, 0, 1024)) != -1) {
                str += new String(readByte).trim();
            }
            return str.getBytes();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * inputStream 轉 Drawable
     * @param inputStream
     * @return Drawable
     */
    public static Drawable getDrawable(InputStream inputStream){
        if (null==inputStream){
            return null;
        }
        Bitmap bitmap = getBitmap(inputStream);
        Drawable drawable = bitmap_Drawable(bitmap);
        return drawable;
    }
    // Bitmap轉換成Drawable
    public static Drawable bitmap_Drawable(Bitmap bitmap) {
        if (null==bitmap){
            return null;
        }
        BitmapDrawable bd = new BitmapDrawable(bitmap);
        Drawable drawable = (Drawable) bd;
        return drawable;
    }

}

可以直接呼叫類中方法即可!
最後Mainactivity 繼承的是自己寫的BaseActivity,用來控制進度條的顯示,有興趣可以下載demo進行測試!
下一篇要研究Handler和Thread的了,come on! 有錯誤多謝大家指正!!!