亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Android使用URLConnection提交請求的實(shí)現(xiàn)

 更新時(shí)間:2017年10月13日 10:04:42   作者:_彼岸雨敲窗_  
這篇文章主要為大家詳細(xì)介紹了Android使用URLConnection提交請求的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

URL的openConnection()方法將返回一個(gè)URLConnection對象,該對象表示應(yīng)用程序和URL之間的通信連接。程序可以通過URLConnection實(shí)例向該URL發(fā)送請求,讀取URL引用的資源。

通常創(chuàng)建一個(gè)和URL的連接,并發(fā)送請求、讀取此URL引用的資源需要如下幾個(gè)步驟:
Step1: 通過調(diào)用URL對象的openConnection()方法來創(chuàng)建URLConnection對象;
Step2:設(shè)置URLConnection的參數(shù)和普通請求屬性;
Step3:如果只是發(fā)送GET方式的請求,那么使用connect方法建立和遠(yuǎn)程資源之間的實(shí)際連接即可;如果需要發(fā)送POST方式的請求,則需要獲取URLConnection實(shí)例對應(yīng)的輸出流來發(fā)送請求參數(shù);
Step4:遠(yuǎn)程資源變?yōu)榭捎茫绦蚩梢栽L問遠(yuǎn)程資源的頭字段,或通過流入流讀取遠(yuǎn)程資源的數(shù)據(jù)。

下面的程序Demo示范了如何向Web站點(diǎn)發(fā)送GET請求、POST請求,并從Web站點(diǎn)取得響應(yīng)。該程序中用到一個(gè)GET、POST請求的工具類,該類代碼如下:

GetPostUtil.java邏輯代碼如下:

package com.fukaimei.getposttest;

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;

/**
 * Created by FuKaimei on 2017/10/2.
 */

public class GetPostUtil {

  private static final String TAG = "GetPostUtil";

  /**
   * 向指定URL發(fā)送GET方式的請求
   *
   * @param url  發(fā)送請求的URL
   * @param params 請求參數(shù),請求參數(shù)應(yīng)該是name1=value1 & name2=value2的形式
   * @return URL所代表遠(yuǎn)程資源的響應(yīng)
   */
  public static String sendGet(String url, String params) {
    String result = "";
    BufferedReader in = null;
    try {
      String urlName = url + "?" + params;
      URL realUrl = new URL(urlName);
      // 打開和URL之間的連接
      URLConnection conn = realUrl.openConnection();
      // 設(shè)置通用的請求屬性
      conn.setRequestProperty("accept", "*/*");
      conn.setRequestProperty("connection", "Keep-Alive");
      conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
      // 建立實(shí)際的連接
      conn.connect();
      // 獲取所有的響應(yīng)頭字段
      Map<String, List<String>> map = conn.getHeaderFields();
      // 遍歷所有的響應(yīng)頭字段
      for (String key : map.keySet()) {
        Log.d(TAG, key + "---->" + map.get(key));
      }
      // 定義BufferedReader輸入流來讀取URL的響應(yīng)
      in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = in.readLine()) != null) {
        result += "\n" + line;
      }
    } catch (Exception e) {
      Log.d(TAG, "發(fā)送GET請求出現(xiàn)異常!" + e);
      e.printStackTrace();
    } finally { // 使用finally塊來關(guān)閉輸入流
      try {
        if (in != null) {
          in.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return result;
  }

  /**
   * 向指定URL發(fā)送POST方式的請求
   *
   * @param url  發(fā)送請求的URL
   * @param params 請求參數(shù),請求參數(shù)應(yīng)該是name1=value1 & name2=value2的形式
   * @return 所代表遠(yuǎn)程資源的響應(yīng)
   */
  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();
      // 設(shè)置通用的請求屬性
      conn.setRequestProperty("accept", "*/*");
      conn.setRequestProperty("connection", "Keep-Alive");
      conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
      // 發(fā)送POST請求必須設(shè)置如下兩行
      conn.setDoOutput(true);
      conn.setDoInput(true);
      // 獲取URLConnection對象對應(yīng)的輸出流
      out = new PrintWriter(conn.getOutputStream());
      // 發(fā)送請求參數(shù)
      out.print(params);
      // flush輸出流的緩存
      out.flush();
      // 定義BufferedReader輸入流來讀取URL的響應(yīng)
      in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = in.readLine()) != null) {
        result += "\n" + line;
      }
    } catch (Exception e) {
      Log.d(TAG, "發(fā)送POST請求出現(xiàn)異常!" + e);
      e.printStackTrace();
    } finally { // 使用finally塊來關(guān)閉輸出流、輸入流
      try {
        if (out != null) {
          out.close();
        }
        if (in != null) {
          in.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return result;
  }
}

從上面的程序Demo可以看出,如果需要發(fā)送GET請求,只要調(diào)用URLConnection的connect()方法去建立實(shí)際的連接即可。如果需要發(fā)送POST請求,則需要獲取URLConnection的OutputStream,然后再向網(wǎng)絡(luò)中輸出請求參數(shù)。
提供了上面發(fā)送GET請求、POST請求的工具類之后,接下來就可以在Activity類中通過該工具類發(fā)送請求了。該程序的界面中包含兩個(gè)按鈕,一個(gè)按鈕用于發(fā)送GET請求,一個(gè)按鈕用于發(fā)送POST請求。程序還提供了一個(gè)EditText來顯示服務(wù)器的響應(yīng)。

layout/activity_main.xml界面布局代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">

  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="horizontal">

    <Button
      android:id="@+id/get"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="發(fā)送GET請求" />

    <Button
      android:id="@+id/post"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="發(fā)送POST請求" />
  </LinearLayout>

  <TextView
    android:id="@+id/show"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffff"
    android:gravity="top"
    android:textColor="#f000"
    android:textSize="16sp" />
</LinearLayout>

MainActivity.java邏輯代碼如下:

package com.fukaimei.getposttest;

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.TextView;

public class MainActivity extends AppCompatActivity {

  Button get, post;
  TextView show;
  // 代表服務(wù)器響應(yīng)的字符串
  String response;
  Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      if (msg.what == 0x123) {
        // 設(shè)置show控件服務(wù)器響應(yīng)
        show.setText(response);
      }
    }
  };

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    get = (Button) findViewById(R.id.get);
    post = (Button) findViewById(R.id.post);
    show = (TextView) findViewById(R.id.show);
    get.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        new Thread() {
          @Override
          public void run() {
            response = GetPostUtil.sendGet("https://www.mi.com/", null);
            // 發(fā)送消息通知UI線程更新UI組件
            handler.sendEmptyMessage(0x123);
          }
        }.start();
      }
    });
    post.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        new Thread() {
          @Override
          public void run() {
            response = GetPostUtil.sendPost("http://172.xx.xx.xxx:8080/fukaimei/login.jsp", "name=android&pass=123");
          }
        }.start();
        // 發(fā)送消息通知UI線程更新UI組件
        handler.sendEmptyMessage(0x123);
      }
    });
  }
}

上面程序Demo中用于發(fā)送GET請求、POST請求。從上面的代碼可以發(fā)現(xiàn),借助于URLConnection類的幫助,應(yīng)用程序可以非常方便地與指定站點(diǎn)交換信息,包括發(fā)送GET請求、POST請求,并獲取網(wǎng)站的響應(yīng)等。

注意:由于該程序需要訪問互聯(lián)網(wǎng),因此還需要在清單文件AndroidManifest.xml文件中授權(quán)訪問互聯(lián)網(wǎng)的權(quán)限:

<!-- 授權(quán)訪問互聯(lián)網(wǎng)-->
  <uses-permission android:name="android.permission.INTERNET" />

Demo程序運(yùn)行效果界面截圖如下:

這里寫圖片描述這里寫圖片描述

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論