1. 程式人生 > >使用 URLConnection提交請求

使用 URLConnection提交請求

GET , POST 請求的工具類

package com.net.httpurl.utils;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

/**
 * GET , POST 請求的工具類
 */
public class GetPostUtils { /** * 向指定url傳送 GET方法的請求 * * @param url 傳送請求的 url * @param params 請求引數 ,格式為 name1 = value1&name2=value2的形式 * @return URL 所代表的遠端資源的響應 */ public static String sendGet(String url, String params) { String result = ""; BufferedReader in = null
; String urlName = url + "?" + params; try { URL realUrl = new URL(urlName); //開啟和URL之間的連線 URLConnection conn = realUrl.openConnection(); //設定通用的請求屬性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection"
, "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); //建立實際連線 conn.connect(); //獲取所有的響應頭欄位 Map<String, List<String>> map = conn.getHeaderFields(); //遍歷 所有的 響應頭欄位 for (String key : map.keySet()) { Log.d("GetPostUtils", key + " ---> " + map.get(key)); } //定義 BufferedReader 輸入流來讀取 URL的響應 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += "\n" + line; } } catch (Exception e) { System.out.println("傳送GET請求出現異常! " + e); e.printStackTrace(); } //使用 finally 關閉輸入流 finally { try { if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } return result; } /** * 向指定URL傳送POST方法的請求 * * @param url url 傳送請求的URL * @param params 請求引數,請求引數應該是name1=value1 & name2=value2的形式。 * @return URL所代表遠端資源的響應 */ public static String sendPost(String url, String params) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); //開啟 url之間的連線 URLConnection conn = realUrl.openConnection(); //設定通用的請求屬性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); //// 傳送POST請求必須設定如下兩行 conn.setDoOutput(true); conn.setDoInput(true); //獲取 URLConnection物件輸出對應的輸出流 out = new PrintWriter(conn.getOutputStream()); //傳送請求餐廚 out.print(params); out.flush(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += "\n" + line; } //建立 } catch (Exception e) { System.out.println("傳送POST請求出現異常!" + e); e.printStackTrace(); } // 使用finally塊來關閉輸出流、輸入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } }

Activity 介面

package com.net.httpurl;

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 com.net.httpurl.utils.GetPostUtils;

/**
 * 使用 UrlConnection 提交請求 169.254.214.117
 * http://169.254.214.117:8080/abc/a.jsp
 */
public class UrlConnectionActivity extends AppCompatActivity {
    Button get, post;
    EditText info, et_url;

    String respone; //代表伺服器響應的資訊
    String url; //代表輸入的 url
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x1234) {
                info.setText(respone); //設定 info 元件顯示伺服器響應
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_url_connection);

        get = (Button) findViewById(R.id.send_get);
        post = (Button) findViewById(R.id.send_post);
        info = (EditText) findViewById(R.id.et_info);
        et_url = (EditText) findViewById(R.id.et_url);

        url = et_url.getText().toString().trim();
        initListener();
    }

    private void initListener() {

        get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        respone = GetPostUtils.sendGet("http://169.254.214.117:8080/abc/a.jsp", null);

                        //傳送訊息通知ui執行緒 ,更新ui介面
                        mHandler.sendEmptyMessage(0x1234);
                    }
                }.start();
            }
        });
        post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        respone = GetPostUtils.sendGet("http://169.254.214.117:8080/abc/login.jsp", "name=admin&pass=test");

                        //傳送訊息通知ui執行緒 ,更新ui介面
                        mHandler.sendEmptyMessage(0x1234);
                    }
                }.start();
            }
        });

    }
}

該程式所傳送的post請求和get請求,是向本地區域網內 "http://169.254.214.117:8080/abc/" 應用下兩個頁面傳送,這個應用是部署在本地計算機上的web應用. 這個應用需要部署在Web伺服器(比如Tomcat)中才可以使用 web應用在tomcat上的部署 ;

單擊按鈕 get請求按鈕 的介面
 get請求按鈕 的介面

單擊按鈕 post請求按鈕 的介面,並提交”name=admin&pass=test”請求引數
post請求按鈕