国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看av不卡

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - 淺談Java HttpURLConnection請求方式

淺談Java HttpURLConnection請求方式

2020-08-25 00:44ouyangjun__ Java教程

這篇文章主要介紹了淺談Java HttpURLConnection請求方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

一)URL代理請求 ?

該方式請求有兩種代理方式。

方式一:使用該方式代理之后,之后的所有接口都會使用代理請求

?
1
2
3
4
5
6
7
// 對http開啟全局代理
System.setProperty("http.proxyHost", "192.168.1.1");
System.setProperty("http.proxyPort", "80");
 
// 對https開啟全局代理
System.setProperty("https.proxyHost", "192.168.1.1");
System.setProperty("https.proxyPort", "80");

方式二:適用于只有部分接口需要代理請求場景

?
1
2
3
4
5
6
7
8
9
10
Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress("192.168.1.1", 80));
HttpURLConnection conn = null;
try {
  URL url = new URL("http://localhost:8080/ouyangjun");
  conn = (HttpURLConnection) url.openConnection(proxy);
} catch (MalformedURLException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

二)無參數GET請求

方法解析:

HttpGetUtils.doGetNoParameters(String requestURL, String proxyHost, Integer proxyPort);

requestURL:請求路徑,必填

proxyHost:代理IP,即服務器代理地址,可為null

proxyPort:代理端口,可為null

說明:一般本地測試幾乎是不會用代理的,只有服務器用代理方式請求比較多。

實現源碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package com.ouyangjun.wechat.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.URL;
 
/**
 * http請求工具類
 * @author ouyangjun
 */
public class HttpGetUtils {
 
  /**
   * http get請求, 不帶參數
   * @param requestURL
   * @param method
   * @return
   */
  public static String doGetNoParameters(String requestURL, String proxyHost, Integer proxyPort) {
    // 記錄信息
    StringBuffer buffer = new StringBuffer();
 
    HttpURLConnection conn = null;
    try {
      URL url = new URL(requestURL);
      // 判斷是否需要代理模式請求http
      if (proxyHost != null && proxyPort != null) {
        // 如果是本機自己測試, 不需要代理請求,但發到服務器上的時候需要代理請求
        // 對http開啟全局代理
        //System.setProperty("http.proxyHost", proxyHost);
        //System.setProperty("http.proxyPort", proxyPort);
        // 對https開啟全局代理
        //System.setProperty("https.proxyHost", proxyHost);
        //System.setProperty("https.proxyPort", proxyPort);
  
        // 代理訪問http請求
        Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        conn = (HttpURLConnection) url.openConnection(proxy);
      } else {
        // 原生訪問http請求,未代理請求
        conn = (HttpURLConnection) url.openConnection();
      }
  
      // 設置請求的屬性
      conn.setDoOutput(true); // 是否可以輸出
      conn.setRequestMethod("GET"); // 請求方式, 只包含"GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE"六種
      conn.setConnectTimeout(60000); // 最高超時時間
      conn.setReadTimeout(60000); // 最高讀取時間
      conn.setConnectTimeout(60000); // 最高連接時間
  
      // 讀取數據
      InputStream is = null;
      InputStreamReader inputReader = null;
      BufferedReader reader = null;
      try {
        is = conn.getInputStream();
        inputReader = new InputStreamReader(is, "UTF-8");
        reader = new BufferedReader(inputReader);
  
        String temp;
        while ((temp = reader.readLine()) != null) {
          buffer.append(temp);
        }
      } catch (Exception e) {
        System.out.println("HttpGetUtils doGetNoParameters error: " + e);
      } finally {
        try {
          if (reader != null) {
            reader.close();
          }
          if (inputReader != null) {
            inputReader.close();
          }
          if (is != null) {
            is.close();
          }
        } catch (IOException e) {
          System.out.println("HttpGetUtils doGetNoParameters error: " + e);
        }
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 當http連接空閑時, 釋放資源
      if (conn != null) {
        conn.disconnect();
      }
    }
    // 返回信息
    return buffer.length()==0 ? "" : buffer.toString();
  }
}

三)帶參數POST請求

方法解析:

HttpPostUtils.doPost(String requestURL, String params, String proxyHost, Integer proxyPort);

requestURL:請求路徑,必填

params:請求參數,必填,數據格式為JSON

proxyHost:代理IP,即服務器代理地址,可為null

proxyPort:代理端口,可為null

說明:一般本地測試幾乎是不會用代理的,只有服務器用代理方式請求比較多。

實現源碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package com.ouyangjun.wechat.utils;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.URL;
 
/**
 * http請求工具類
 * @author ouyangjun
 */
public class HttpPostUtils {
 
  /**
   * http post請求, 帶參數
   * @param requestURL
   * @param params
   * @return
   */
  public static String doPost(String requestURL, String params, String proxyHost, Integer proxyPort) {
    // 記錄信息
    StringBuffer buffer = new StringBuffer();
 
    HttpURLConnection conn = null;
    try {
      URL url = new URL(requestURL);
      // 判斷是否需要代理模式請求http
      if (proxyHost != null && proxyPort != null) {
        // 如果是本機自己測試, 不需要代理請求,但發到服務器上的時候需要代理請求
        // 對http開啟全局代理
        //System.setProperty("http.proxyHost", proxyHost);
        //System.setProperty("http.proxyPort", proxyPort);
        // 對https開啟全局代理
        //System.setProperty("https.proxyHost", proxyHost);
        //System.setProperty("https.proxyPort", proxyPort);
  
        // 代理訪問http請求
        Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        conn = (HttpURLConnection) url.openConnection(proxy);
      } else {
        // 原生訪問http請求,未代理請求
        conn = (HttpURLConnection) url.openConnection();
      }
  
      // 設置請求的屬性
      conn.setDoOutput(true); // 是否可以輸出
      conn.setRequestMethod("POST"); // 請求方式, 只包含"GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE"六種
      conn.setConnectTimeout(60000); // 最高超時時間
      conn.setReadTimeout(60000); // 最高讀取時間
      conn.setConnectTimeout(60000); // 最高連接時間
  
      conn.setDoInput(true); // 是否可以輸入
      if (params != null) {
        // 設置參數為json格式
        conn.setRequestProperty("Content-type", "application/json");
  
        // 寫入參數信息
        OutputStream os = conn.getOutputStream();
        try {
          os.write(params.getBytes("UTF-8"));
        } catch (Exception e) {
          System.out.println("HttpPostUtils doPost error: " + e);
        } finally {
          try {
            if (os != null) {
              os.close();
            }
          } catch (IOException e) {
            System.out.println("HttpPostUtils doPost error: " + e);
          }
        }
      }
  
      // 讀取數據
      InputStream is = null;
      InputStreamReader inputReader = null;
      BufferedReader reader = null;
      try {
        is = conn.getInputStream();
        inputReader = new InputStreamReader(is, "UTF-8");
        reader = new BufferedReader(inputReader);
  
        String temp;
        while ((temp = reader.readLine()) != null) {
          buffer.append(temp);
        }
      } catch (Exception e) {
        System.out.println("HttpPostUtils doPost error: " + e);
      } finally {
        try {
          if (reader != null) {
            reader.close();
          }
          if (inputReader != null) {
            inputReader.close();
          }
          if (is != null) {
            is.close();
          }
        } catch (IOException e) {
          System.out.println("HttpPostUtils doPost error: " + e);
        }
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 當http連接空閑時, 釋放資源
      if (conn != null) {
        conn.disconnect();
      }
    }
    // 返回信息
    return buffer.length()==0 ? "" : buffer.toString();
  }
}

四)Http模擬測試

本案例是使用了微信公眾號兩個接口作為了測試案例。

appID和appsecret需要申請了微信公眾號才能獲取到。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.ouyangjun.wechat.test;
import com.ouyangjun.wechat.utils.HttpGetUtils;
import com.ouyangjun.wechat.utils.HttpPostUtils;
 
public class TestHttp {
 
  private final static String WECHAT_APPID=""; // appid, 需申請微信公眾號才能拿到
  private final static String WECHAT_APPSECRET=""; // appsecret, 需申請微信公眾號才能拿到
 
  public static void main(String[] args) {
    // 獲取微信公眾號token
    getWeChatToken();
 
    // 修改用戶備注信息
    String token = "31_1uw5em_HrgkfXok6drZkDZLKsBfbNJr9WTdzdkc_Tdat-9tpOezWsNI6tBMkyPe_zDHjErIS1r0dgnTpT5bfKXcASShJVhPqumivRP21PvQe3Cbfztgs1IL2Jpy7kw3Y09bC1urlWzDA52mtEDGcADAVUX";
    String openid = "oCh4n0-6JKQpJgBOPA5tytoYb0VY";
    updateUserRemark(token, openid);
  }
 
  /**
   * 根據appid和appsecret獲取微信token,返回json格式數據,需自行解析
   * @return
   */
  public static String getWeChatToken() {
    String requestURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+WECHAT_APPID+"&secret="+WECHAT_APPSECRET;
 
    String token = HttpGetUtils.doGetNoParameters(requestURL, null, null);
    System.out.println("wechat token: " + token);
    return token;
  }
 
  /**
   * 修改用戶備注,返回json格式數據,需自行解析
   * @param token
   * @param openid
   * @return
   */
  public static String updateUserRemark(String token, String openid) {
    // 封裝json參數
    String jsonParams = "{\"openid\":\""+openid+"\",\"remark\":\"oysept\"}";
 
    String msg = HttpPostUtils.doPost(reuqestURL, jsonParams, null, null);
    System.out.println("msg: " + msg);
    return jsonParams;
  }
}

補充知識:Java HttpURLConnection post set params 設置請求參數的三種方法 實踐總結

我就廢話不多說了,大家還是直接看代碼吧~

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
 * the first way to set params
 * OutputStream
 */
 
byte[] bytesParams = paramsStr.getBytes();
// 發送請求params參數
OutputStream outStream=connection.getOutputStream();
outStream.write(bytesParams);
outStream.flush();
 
/**
 * the second way to set params
 * PrintWriter
 */
 
 PrintWriter printWriter = new PrintWriter(connection.getOutputStream());
//PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(),"UTF-8"));
// 發送請求params參數
printWriter.write(paramsStr);
printWriter.flush();
 
/**
 * the third way to set params
 * OutputStreamWriter
 */
OutputStreamWriter out = new OutputStreamWriter(
    connection.getOutputStream(), "UTF-8");
// 發送請求params參數
out.write(paramsStr);
out.flush();

demo:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/**
  * @param pathurl
  * @param paramsStr
  * @return
  */
 private static String postUrlBackStr(String pathurl, String paramsStr) {
   String backStr = "";
   InputStream inputStream = null;
   ByteArrayOutputStream baos = null;
   try {
     URL url = new URL(pathurl);
     HttpURLConnection connection = (HttpURLConnection) url.openConnection();
     // 設定請求的方法為"POST",默認是GET
     connection.setRequestMethod("POST");
     connection.setConnectTimeout(50000);
     connection.setReadTimeout(50000);
    // User-Agent IE11 的標識
     connection.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.3; Trident/7.0;rv:11.0)like Gecko");
     connection.setRequestProperty("Accept-Language", "zh-CN");
     connection.setRequestProperty("Connection", "Keep-Alive");
     connection.setRequestProperty("Charset", "UTF-8");
     /**
      * 當我們要獲取我們請求的http地址訪問的數據時就是使用connection.getInputStream().read()方式時我們就需要setDoInput(true),
      根據api文檔我們可知doInput默認就是為true。我們可以不用手動設置了,如果不需要讀取輸入流的話那就setDoInput(false)。
 
      當我們要采用非get請求給一個http網絡地址傳參 就是使用connection.getOutputStream().write() 方法時我們就需要setDoOutput(true), 默認是false
      */
     // 設置是否從httpUrlConnection讀入,默認情況下是true;
     connection.setDoInput(true);
     // 設置是否向httpUrlConnection輸出,如果是post請求,參數要放在http正文內,因此需要設為true, 默認是false;
     connection.setDoOutput(true);
     connection.setUseCaches(false);
 
     /**
      * the first way to set params
      * OutputStream
      */
    /*  byte[] bytesParams = paramsStr.getBytes();
     // 發送請求params參數
     OutputStream outStream=connection.getOutputStream();
     outStream.write(bytesParams);
     outStream.flush();
     */
 
     /**
      * the second way to set params
      * PrintWriter
      */
     /* PrintWriter printWriter = new PrintWriter(connection.getOutputStream());
     //PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(),"UTF-8"));
     // 發送請求params參數
     printWriter.write(paramsStr);
     printWriter.flush();*/
 
     /**
      * the third way to set params
      * OutputStreamWriter
      */
     OutputStreamWriter out = new OutputStreamWriter(
         connection.getOutputStream(), "UTF-8");
     // 發送請求params參數
     out.write(paramsStr);
     out.flush();
 
 
     connection.connect();//
     int contentLength = connection.getContentLength();
     if (connection.getResponseCode() == 200) {
       inputStream = connection.getInputStream();//會隱式調用connect()
       baos = new ByteArrayOutputStream();
       int readLen;
       byte[] bytes = new byte[1024];
       while ((readLen = inputStream.read(bytes)) != -1) {
         baos.write(bytes, 0, readLen);
       }
       backStr = baos.toString();
       Log.i(TAG, "backStr:" + backStr);
 
     } else {
       Log.e(TAG, "請求失敗 code:" + connection.getResponseCode());
     }
 
   } catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       if (baos != null) {
         baos.close();
       }
       if (inputStream != null) {
         inputStream.close();
       }
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   return backStr;
 }

以上這篇淺談Java HttpURLConnection請求方式就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。

原文鏈接:https://blog.csdn.net/p812438109/article/details/105105188

延伸 · 閱讀

精彩推薦
Weibo Article 1 Weibo Article 2 Weibo Article 3 Weibo Article 4 Weibo Article 5 Weibo Article 6 Weibo Article 7 Weibo Article 8 Weibo Article 9 Weibo Article 10 Weibo Article 11 Weibo Article 12 Weibo Article 13 Weibo Article 14 Weibo Article 15 Weibo Article 16 Weibo Article 17 Weibo Article 18 Weibo Article 19 Weibo Article 20 Weibo Article 21 Weibo Article 22 Weibo Article 23 Weibo Article 24 Weibo Article 25 Weibo Article 26 Weibo Article 27 Weibo Article 28 Weibo Article 29 Weibo Article 30 Weibo Article 31 Weibo Article 32 Weibo Article 33 Weibo Article 34 Weibo Article 35 Weibo Article 36 Weibo Article 37 Weibo Article 38 Weibo Article 39 Weibo Article 40
主站蜘蛛池模板: 成人免费观看www的片 | 激情五月综合网 | 寡妇少妇高潮免费看蜜臀a 午夜免费电影 | 午夜精品久久久久久久 | 日韩精品一区二 | 青青草网站| 日韩中文字幕在线免费观看 | 国产精品剧情一区二区三区 | 亚洲综合大片69999 | 久草电影网 | 日韩免费高清视频 | 成人在线观看h | 日本精品一区二区三区在线观看视频 | 国产欧美日韩一区二区三区四区 | 欧洲精品 | 91观看| 免费在线黄色片 | 国产一区二区三区视频在线观看 | 欧美精品一区二区三区四区五区 | 精品视频第一页 | 99久久精品一区二区成人 | 亚洲久久一区二区 | 欧美在线不卡 | 欧洲一区二区三区 | 国产人免费人成免费视频 | 中文字幕第一页在线 | 毛片首页| 91视频观看| av网站观看| 国产一区二区三区在线视频 | 久久99这里只有精品 | 国产一级特黄 | 成人一区二区三区 | 国产精品久久久久久久久 | 成人av电影网 | 国产一区二区黑人欧美xxxx | 国产精品视频久久久 | 久久久久久亚洲精品中文字幕 | 欧美午夜在线 | 亚洲在线视频播放 | 中文字幕一区二区三区在线视频 |