java調用http接口的幾種方式總結

本文參考: https://blog.csdn.net/fightingXia/article/details/71775516html

     https://www.cnblogs.com/jeffen/p/6937788.htmljava

 

隨着網絡上java應用愈來愈多,場景愈來愈複雜,因此應用之間常常經過HTTP接口來訪問資源web

 

首先了解了URL的最經常使用的兩種請求方式:第一種GET,第二種POSTjson

GET:get請求能夠獲取頁面,也能夠把參數放到URL後面以?分割傳遞數據,參數之間以&關聯,例如 http://110.32.44.11:8086/sp-test/usertest/1.0/query?mobile=15334567890&name=zhansan瀏覽器

POST:post請求的參數是放在HTTP請求的正文裏,請求的參數被封裝起來經過流的方式傳遞緩存

 

1.HttpURLConnection 服務器

  1.1簡介:微信

    在java.net包中,已經提供訪問HTTP協議的基本功能類:HttpURLConnection,能夠向其餘系統發送GET,POST訪問請求網絡

  1.2 GET方式調用併發

    

 1     private void httpURLGETCase() {
 2         String methodUrl = "http://110.32.44.11:8086/sp-test/usertest/1.0/query";
 3         HttpURLConnection connection = null;
 4         BufferedReader reader = null;
 5         String line = null;
 6         try {
 7             URL url = new URL(methodUrl + "?mobile=15334567890&name=zhansan");
 8             connection = (HttpURLConnection) url.openConnection();// 根據URL生成HttpURLConnection
 9             connection.setRequestMethod("GET");// 默認GET請求
10             connection.connect();// 創建TCP鏈接
11             if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
12                 reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));// 發送http請求
13                 StringBuilder result = new StringBuilder();
14                 // 循環讀取流
15                 while ((line = reader.readLine()) != null) {
16                     result.append(line).append(System.getProperty("line.separator"));// "\n"
17                 }
18                 System.out.println(result.toString());
19             }
20         } catch (IOException e) {
21             e.printStackTrace();
22         } finally {
23             try {
24                 reader.close();
25             } catch (IOException e) {
26                 e.printStackTrace();
27             }
28             connection.disconnect();
29         }
30     }

 

  1.3 POST方式調用

    1.3.1 帶受權的傳遞json格式參數調用

 1     private static void httpURLPOSTCase() {
 2         String methodUrl = "http://xxx.xxx.xx.xx:8280/xx/adviserxx/1.0 ";
 3         HttpURLConnection connection = null;
 4         OutputStream dataout = null;
 5         BufferedReader reader = null;
 6         String line = null;
 7         try {
 8             URL url = new URL(methodUrl);
 9             connection = (HttpURLConnection) url.openConnection();// 根據URL生成HttpURLConnection
10             connection.setDoOutput(true);// 設置是否向connection輸出,由於這個是post請求,參數要放在http正文內,所以須要設爲true,默認狀況下是false
11             connection.setDoInput(true); // 設置是否從connection讀入,默認狀況下是true;
12             connection.setRequestMethod("POST");// 設置請求方式爲post,默認GET請求
13             connection.setUseCaches(false);// post請求不能使用緩存設爲false
14             connection.setConnectTimeout(3000);// 鏈接主機的超時時間
15             connection.setReadTimeout(3000);// 從主機讀取數據的超時時間
16             connection.setInstanceFollowRedirects(true);// 設置該HttpURLConnection實例是否自動執行重定向
17             connection.setRequestProperty("connection", "Keep-Alive");// 鏈接複用
18             connection.setRequestProperty("charset", "utf-8");
19             
20             connection.setRequestProperty("Content-Type", "application/json");
21             connection.setRequestProperty("Authorization", "Bearer 66cb225f1c3ff0ddfdae31rae2b57488aadfb8b5e7");
22             connection.connect();// 創建TCP鏈接,getOutputStream會隱含的進行connect,因此此處能夠不要
23 
24             dataout = new DataOutputStream(connection.getOutputStream());// 建立輸入輸出流,用於往鏈接裏面輸出攜帶的參數
25             String body = "[{\"orderNo\":\"44921902\",\"adviser\":\"張怡筠\"}]";
26             dataout.write(body.getBytes());
27             dataout.flush();
28             dataout.close();
29 
30             if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
31                 reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));// 發送http請求
32                 StringBuilder result = new StringBuilder();
33                 // 循環讀取流
34                 while ((line = reader.readLine()) != null) {
35                     result.append(line).append(System.getProperty("line.separator"));//
36                 }
37                 System.out.println(result.toString());
38             }
39         } catch (IOException e) {
40             e.printStackTrace();
41         } finally {
42             try {
43                 reader.close();
44             } catch (IOException e) {
45                 e.printStackTrace();
46             }
47             connection.disconnect();
48         }
49     }

 

    1.3.2 傳遞鍵值對的參數

            URL url = new URL(getUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST"); 
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.connect();

            String body = "userName=zhangsan&password=123456";
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
            writer.write(body);
            writer.close();

    1.3.3 在post請求上傳文件

try {
    URL url = new URL(getUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setUseCaches(false);
    connection.setRequestProperty("Content-Type", "file/*");//設置數據類型
    connection.connect();

    OutputStream outputStream = connection.getOutputStream();
    FileInputStream fileInputStream = new FileInputStream("file");//把文件封裝成一個流
    int length = -1;
    byte[] bytes = new byte[1024];
    while ((length = fileInputStream.read(bytes)) != -1){
        outputStream.write(bytes,0,length);//寫的具體操做
    }
    fileInputStream.close();
    outputStream.close();

    int responseCode = connection.getResponseCode();
    if(responseCode == HttpURLConnection.HTTP_OK){
        InputStream inputStream = connection.getInputStream();
        String result = is2String(inputStream);//將流轉換爲字符串。
        Log.d("kwwl","result============="+result);
    }

} catch (Exception e) {
    e.printStackTrace();
}

    1.3.4 同時上傳參數和文件

在實際應用時,上傳文件的同時也經常須要上傳鍵值對參數。好比在微信中發朋友圈時,不只有圖片,還有有文字。此時就須要同時上傳參數和文件。

在httpURLconnection中並無提供直接上傳參數和文件的API,須要咱們本身去探索。咱們知道在Web頁面上傳參數和文件很簡單,只須要在form標籤寫上contentype=」multipart/form-data」便可,剩餘工做便都交給瀏覽器去完成數據收集併發送Http請求。可是若是沒有頁面的話要怎麼上傳文件呢?

因爲脫離了瀏覽器的環境,咱們就要本身去完成數據的封裝併發送。首先咱們來看web頁面上傳參數和文件是什麼樣子的?

咱們寫一個web表單,上傳兩個鍵值對參數和一個文件。使用抓包工具抓取的數據結果以下:

這裏寫圖片描述 

通過分析可知,上傳到服務器的數據除了鍵值對數據和文件數據外,還有其餘字符串,使用這些這些字符串來拼接必定的格式。

那麼咱們只要模擬這個數據,並寫入到Http請求中便能實現同時傳遞參數和文件。

代碼以下:

try {

    String BOUNDARY = java.util.UUID.randomUUID().toString();
    String TWO_HYPHENS = "--";
    String LINE_END = "\r\n";

    URL url = new URL(URLContant.CHAT_ROOM_SUBJECT_IMAGE);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setUseCaches(false);

    //設置請求頭
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Charset", "UTF-8");
    connection.setRequestProperty("Content-Type","multipart/form-data; BOUNDARY=" + BOUNDARY);
    connection.setRequestProperty("Authorization","Bearer "+UserInfoConfigure.authToken);
    connection.connect();

    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    StringBuffer strBufparam = new StringBuffer();
    //封裝鍵值對數據一
    strBufparam.append(TWO_HYPHENS);
    strBufparam.append(BOUNDARY);
    strBufparam.append(LINE_END);
    strBufparam.append("Content-Disposition: form-data; name=\"" + "groupId" + "\"");
    strBufparam.append(LINE_END);
    strBufparam.append("Content-Type: " + "text/plain" );
    strBufparam.append(LINE_END);
    strBufparam.append("Content-Lenght: "+(""+groupId).length());
    strBufparam.append(LINE_END);
    strBufparam.append(LINE_END);
    strBufparam.append(""+groupId);
    strBufparam.append(LINE_END);

    //封裝鍵值對數據二
    strBufparam.append(TWO_HYPHENS);
    strBufparam.append(BOUNDARY);
    strBufparam.append(LINE_END);
    strBufparam.append("Content-Disposition: form-data; name=\"" + "title" + "\"");
    strBufparam.append(LINE_END);
    strBufparam.append("Content-Type: " + "text/plain" );
    strBufparam.append(LINE_END);
    strBufparam.append("Content-Lenght: "+"kwwl".length());
    strBufparam.append(LINE_END);
    strBufparam.append(LINE_END);
    strBufparam.append("kwwl");
    strBufparam.append(LINE_END);

    //拼接完成後,一塊寫入
    outputStream.write(strBufparam.toString().getBytes());


    //拼接文件的參數
    StringBuffer strBufFile = new StringBuffer();
    strBufFile.append(LINE_END);
    strBufFile.append(TWO_HYPHENS);
    strBufFile.append(BOUNDARY);
    strBufFile.append(LINE_END);
    strBufFile.append("Content-Disposition: form-data; name=\"" + "image" + "\"; filename=\"" + file.getName() + "\"");
    strBufFile.append(LINE_END);
    strBufFile.append("Content-Type: " + "image/*" );
    strBufFile.append(LINE_END);
    strBufFile.append("Content-Lenght: "+file.length());
    strBufFile.append(LINE_END);
    strBufFile.append(LINE_END);

    outputStream.write(strBufFile.toString().getBytes());

    //寫入文件
    FileInputStream fileInputStream = new FileInputStream(file);
    byte[] buffer = new byte[1024*2];
    int length = -1;
    while ((length = fileInputStream.read(buffer)) != -1){
        outputStream.write(buffer,0,length);
    }
    outputStream.flush();
    fileInputStream.close();

    //寫入標記結束位
    byte[] endData = (LINE_END + TWO_HYPHENS + BOUNDARY + TWO_HYPHENS + LINE_END).getBytes();//寫結束標記位
    outputStream.write(endData);
    outputStream.flush();

    //獲得響應
    int responseCode = connection.getResponseCode();
    if(responseCode == HttpURLConnection.HTTP_OK){
        InputStream inputStream = connection.getInputStream();
        String result = is2String(inputStream);//將流轉換爲字符串。
        Log.d("kwwl","result============="+result);
    }

} catch (Exception e) {
    e.printStackTrace();
}

demo2

    private static String imageIdentify(String card,String methodUrl, byte[] fileBytes, String file_id) {
        HttpURLConnection connection = null;
        OutputStream dataout = null;
        BufferedReader bf = null;
        String BOUNDARY = "----WebKitFormBoundary2NYA7hQkjRHg5WJk";
        String END_DATA = ("\r\n--" + BOUNDARY + "--\r\n");
        String BOUNDARY_PREFIX = "--";
        String NEW_LINE = "\r\n";
        try {
            URL url = new URL(methodUrl+"?card="+card);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(3000);
            connection.setReadTimeout(3000);
            connection.setDoOutput(true);// 設置鏈接輸出流爲true,默認false
            connection.setDoInput(true);// 設置鏈接輸入流爲true
            connection.setRequestMethod("POST");// 設置請求方式爲post
            connection.setUseCaches(false);// post請求緩存設爲false
            connection.setInstanceFollowRedirects(true);// 設置該HttpURLConnection實例是否自動執行重定向
            connection.setRequestProperty("connection", "Keep-Alive");// 鏈接複用
            connection.setRequestProperty("charset", "utf-8");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);
            connection.connect();// 創建鏈接

            dataout = new DataOutputStream(connection.getOutputStream());// 建立輸入輸出流,用於往鏈接裏面輸出攜帶的參數
            StringBuilder sb2 = new StringBuilder();
            sb2.append(BOUNDARY_PREFIX);
            sb2.append(BOUNDARY);
            sb2.append(NEW_LINE);
            sb2.append("Content-Disposition:form-data; name=\"type\"");
            // 參數頭設置完成後須要2個換行,纔是內容
            sb2.append(NEW_LINE);
            sb2.append(NEW_LINE);
            sb2.append("0");
            sb2.append(NEW_LINE);
            dataout.write(sb2.toString().getBytes());

            // 讀取文件上傳到服務器
            StringBuilder sb1 = new StringBuilder();
            sb1.append(BOUNDARY_PREFIX);
            sb1.append(BOUNDARY);
            sb1.append(NEW_LINE);
            sb1.append("Content-Disposition:form-data; name=\"file\";filename=\"" + file_id + "\"");//文件名必須帶後綴
            sb1.append(NEW_LINE);
            sb1.append("Content-Type:application/octet-stream");
            // 參數頭設置完成後須要2個換行,纔是內容
            sb1.append(NEW_LINE);
            sb1.append(NEW_LINE);
            dataout.write(sb1.toString().getBytes());
            dataout.write(fileBytes);// 寫文件字節
            
            dataout.write(NEW_LINE.getBytes());
            dataout.write(END_DATA.getBytes());
            dataout.flush();
            dataout.close();

            bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));// 鏈接發起請求,處理服務器響應
            String line;
            StringBuilder result = new StringBuilder(); // 用來存儲響應數據
            // 循環讀取流,若不到結尾處
            while ((line = bf.readLine()) != null) {
                result.append(line).append(System.getProperty("line.separator"));
            }
            bf.close();
            connection.disconnect(); // 銷燬鏈接
            return result.toString();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return "";
    }

    1.3.4

從服務器下載文件是比較簡單的操做,只要獲得輸入流,就能夠從流中讀出數據。使用示例以下:

try {
     String urlPath = "https://www.baidu.com/";
      URL url = new URL(urlPath);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setRequestMethod("GET");
      connection.connect();
      int responseCode = connection.getResponseCode();
      if(responseCode == HttpURLConnection.HTTP_OK){
          InputStream inputStream = connection.getInputStream();
          File dir = new File("fileDir");
          if (!dir.exists()){
              dir.mkdirs();
          }
          File file = new File(dir, "fileName");//根據目錄和文件名獲得file對象
          FileOutputStream fos = new FileOutputStream(file);
          byte[] buf = new byte[1024*8];
          int len = -1;
          while ((len = inputStream.read(buf)) != -1){
              fos.write(buf, 0, len);
          }
          fos.flush();
      }

  } catch (Exception e) {
      e.printStackTrace();
  }

 

 

 

 

 

2.HttpClient

  2.1簡介:

     

  2.2 GET方式調用

 

  2.3 POST方式調用

 

3.Spring RestTemplate

  3.1簡介:

     

  3.2 GET方式調用

  3.3 POST方式調用

相關文章
相關標籤/搜索