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"; } } 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM