1. 程式人生 > 實用技巧 >java http的get、post、post json引數的方法

java http的get、post、post json引數的方法

對於http的post json引數方法使用的是Apache的HttpClient-4.x.Jar,先引入jar

在maven新增如下:

      <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
   <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version
>4.5.12</version> </dependency>

使用Apache的HttpClient-4.x.Jar包。

Jar包Maven下載地址:https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient

1、先建立HttpUtil 工具類:

package com.game.www.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.MalformedURLException; import java.net.URL; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.HTTP; import com.alibaba.fastjson.JSONObject; public class HttpUtil { public static String doGet(String httpurl) { HttpURLConnection connection = null; InputStream is = null; BufferedReader br = null; String result = null;// 返回結果字串 try { // 建立遠端url連線物件 URL url = new URL(httpurl); // 通過遠端url連線物件開啟一個連線,強轉成httpURLConnection類 connection = (HttpURLConnection) url.openConnection(); // 設定連線方式:get connection.setRequestMethod("GET"); // 設定連線主機伺服器的超時時間:15000毫秒 connection.setConnectTimeout(15000); // 設定讀取遠端返回的資料時間:60000毫秒 connection.setReadTimeout(60000); // 傳送請求 connection.connect(); // 通過connection連線,獲取輸入流 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 封裝輸入流is,並指定字符集 br = new BufferedReader(new InputStreamReader(is, "UTF-8")); // 存放資料 StringBuffer sbf = new StringBuffer(); String temp = null; while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 關閉資源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } connection.disconnect();// 關閉遠端連線 } return result; } public static String doPost(String httpUrl, String param) { HttpURLConnection connection = null; InputStream is = null; OutputStream os = null; BufferedReader br = null; String result = null; try { URL url = new URL(httpUrl); // 通過遠端url連線物件開啟連線 connection = (HttpURLConnection) url.openConnection(); // 設定連線請求方式 connection.setRequestMethod("POST"); // 設定連線主機伺服器超時時間:15000毫秒 connection.setConnectTimeout(150000); // 設定讀取主機伺服器返回資料超時時間:60000毫秒 connection.setReadTimeout(600000); // 預設值為:false,當向遠端伺服器傳送資料/寫資料時,需要設定為true connection.setDoOutput(true); // 預設值為:true,當前向遠端服務讀取資料時,設定為true,該引數可有可無 connection.setDoInput(true); // 設定傳入引數的格式:請求引數應該是 name1=value1&name2=value2 的形式。 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 設定鑑權資訊:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0 connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0"); // 通過連線物件獲取一個輸出流 os = connection.getOutputStream(); // 通過輸出流物件將引數寫出去/傳輸出去,它是通過位元組陣列寫出的 os.write(param.getBytes()); // 通過連線物件獲取一個輸入流,向遠端讀取 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 對輸入流物件進行包裝:charset根據工作專案組的要求來設定 br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuffer sbf = new StringBuffer(); String temp = null; // 迴圈遍歷一行一行讀取資料 while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 關閉資源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } // 斷開與遠端地址url的連線 connection.disconnect(); } return result; } /** * 傳送post請求 * @param URL * @param json * * @return */ public static String sendPost(String URL,JSONObject json) { CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(URL); post.setHeader("Content-Type", "application/json"); post.addHeader("Authorization", "Basic YWRtaW46"); String result; try { StringEntity s = new StringEntity(json.toString(), "utf-8"); s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(s); // 傳送請求 HttpResponse httpResponse = client.execute(post); // 獲取響應輸入流 InputStream inStream = httpResponse.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader( inStream, "utf-8")); StringBuilder strber = new StringBuilder(); String line; while ((line = reader.readLine()) != null) strber.append(line + "\n"); inStream.close(); result = strber.toString(); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { System.out.println("請求伺服器成功,做相應處理"); } else { System.out.println("請求服務端失敗"); } } catch (Exception e) { // logger.error("請求異常:"+e.getMessage()); throw new RuntimeException(e); } return result; } }

2、spring mvc 的controller 測試案例:

    @RequestMapping(value = "/get", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    @ResponseBody
    @ApiOperation(value = "get", notes = "get")
    @ApiResponse(response= String.class, code = 200, message = "介面返回物件引數")
    public String get(HttpServletRequest request, HttpServletResponse response) {
        
        try {
            String url = "http://11.29.11.19:8080/Inv/baseData/action/getList";
            String result = HttpUtil.doGet(url);
            
            return result;
        
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }
    
    @RequestMapping(value = "/post", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    @ResponseBody
    @ApiOperation(value = "post", notes = "post")
    @ApiResponse(response= String.class, code = 200, message = "介面返回物件引數")
    public String post(HttpServletRequest request, HttpServletResponse response) {
        
        try {
            String url = "http://11.29.11.19:8080/Inv/baseData/action/query";
            String p = "limit=10&offset=2";
            String result = HttpUtil.doPost(url, p);
        
            return result;
        
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }
    
    
    @RequestMapping(value = "/postJson", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    @ResponseBody
    @ApiOperation(value = "postJson", notes = "postJson")
    @ApiResponse(response= String.class, code = 200, message = "介面返回物件引數")
    public String postJson(HttpServletRequest request, HttpServletResponse response) {
        
        try {
            String url = "http://11.29.11.19:8080/my/api/user/login";
            
            JSONObject jsonObject = new JSONObject();
            
            jsonObject.put("loginname", "123456");
            jsonObject.put("pwd", "123456");
            String result = HttpUtil.sendPost(url,jsonObject);
        
            return result;
        
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }