【Java】【20】後臺發送GET/POST方法

前言:html

1,get請求java

2,post請求node

3,post,get通用方法apache

4,其餘的get,post寫法json

通過一段時間的檢驗,用方法3吧,比較好用。app

 

【Java】【29】post,get通用方法增強 - 花生喂龍 - 博客園
https://www.cnblogs.com/huashengweilong/p/11028200.htmldom

 

正文:post

1,get請求ui

import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; // HTTP GET request
public static String SendGet(String url) { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.error("獲取SendGet失敗:" + method.getStatusLine()); } return method.getResponseBodyAsString(); } catch (HttpException e) { logger.error("獲取SendGet失敗: Fatal protocol violation", e); } catch (IOException e) { logger.error("獲取SendGet失敗: transport error", e); } finally { method.releaseConnection(); } return ""; }

2,post請求編碼

// HTTP POST
public static String SendPOST(String url) { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.error("獲取SendPOST失敗:" + method.getStatusLine()); } return method.getResponseBodyAsString(); } catch (HttpException e) { logger.error("獲取SendPOST失敗: Fatal protocol violation", e); } catch (IOException e) { logger.error("獲取SendPOST失敗: transport error", e); } finally { method.releaseConnection(); } return ""; }

3,post,get通用方法

(1)返回的是json格式數據。根據個人使用狀況來看,若是返回的是list數據,是要用JSONArray格式接收的,若是是多參數,用JSONObject。如今接口通常都會返回請求狀態和錯誤緣由及數據,因此用JSONObject接收就能夠了

(2)HttpURLConnection表明請求的是http的URL,若是是https,須要用HttpsURLConnection

import net.sf.json.JSONObject; import java.io.*; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.URL; //post,get通用方法
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) { JSONObject jsonObject = null; StringBuffer buffer = new StringBuffer(); try { URL url= new URL(requestUrl); HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); //設置請求方式(GET/POST)
 httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect(); //當有數據須要提交時
        if (null != outputStr) { OutputStream outputStream = httpUrlConn.getOutputStream(); //注意編碼格式,防止中文亂碼
            outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); } //將返回的輸入流轉換成字符串
        InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); //釋放資源
 inputStream.close(); httpUrlConn.disconnect(); jsonObject = JSONObject.fromObject(buffer.toString()); } catch (ConnectException ce) { logger.info("httpRequest: Weixin server connection timed out."); } catch (Exception e) { logger.info("httpRequest: error:{}" + e); } return jsonObject; }

https的請求方法,大同小異

import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; //post,get通用方法
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) { JSONObject jsonObject = null; StringBuffer buffer = new StringBuffer(); try { //建立SSLContext對象,並使用咱們指定的信任管理器初始化 
        TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); //從上述SSLContext對象中獲得SSLSocketFactory對象 
        SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl); HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection(); httpUrlConn.setSSLSocketFactory(ssf); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); //設置請求方式(GET/POST) 
 httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect(); //當有數據須要提交時 
        if (null != outputStr) { OutputStream outputStream = httpUrlConn.getOutputStream(); //注意編碼格式,防止中文亂碼 
            outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); } //將返回的輸入流轉換成字符串 
        InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); //釋放資源 
 inputStream.close(); inputStream = null; httpUrlConn.disconnect(); jsonObject = JSONObject.fromObject(buffer.toString()); } catch (ConnectException ce) { logger.info("httpRequest: Weixin server connection timed out."); } catch (Exception e) { logger.info("httpRequest: error:{}" + e); } return jsonObject; } 
MyX509TrustManager.class
import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; /** * 證書信任管理器(用於https請求) * */  
public class MyX509TrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } } 

4,其餘的get,post寫法

/** * 向指定URL發送GET方法的請求 * * @param url * 發送請求的URL * @param param * 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。 * @return URL 所表明遠程資源的響應結果 */
    public static String sendGet(String url, String param) { String result = ""; BufferedReader in = null; try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); // 打開和URL之間的鏈接
            URLConnection connection = realUrl.openConnection(); // 設置通用的請求屬性
            connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); // 創建實際的鏈接
 connection.connect(); // 獲取全部響應頭字段
            Map<String, List<String>> map = connection.getHeaderFields(); // 遍歷全部的響應頭字段
            for (String key : map.keySet()) { map.get(key); } // 定義 BufferedReader輸入流來讀取URL的響應
            in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { logger.info("發送GET請求出現異常:" + e); e.printStackTrace(); } // 使用finally塊來關閉輸入流
        finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; }

 

/** * 向指定 URL 發送POST方法的請求 * * @param url * 發送請求的 URL * @param param * 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。 * @return 所表明遠程資源的響應結果 */
    public static String sendPost(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打開和URL之間的鏈接
            URLConnection conn = realUrl.openConnection(); // 設置通用的請求屬性
            conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 發送POST請求必須設置以下兩行
            conn.setDoOutput(true); conn.setDoInput(true); // 獲取URLConnection對象對應的輸出流
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8")); // 發送請求參數
 out.print(param); // flush輸出流的緩衝
 out.flush(); // 定義BufferedReader輸入流來讀取URL的響應
            in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { logger.info("發送 POST 請求出現異常:"+e); e.printStackTrace(); } //使用finally塊來關閉輸出流、輸入流
        finally{ try{ if(out!=null){ out.close(); } if(in!=null){ in.close(); } } catch(IOException ex){ ex.printStackTrace(); } } return result; }

參考博客:

1,JAVA利用HttpClient進行HTTPS接口調用 - 路常有 - 博客園
https://www.cnblogs.com/luchangyou/p/6375166.html

2,使用httpclient實現後臺java發送post和get請求 - myrui422的博客 - CSDN博客
https://blog.csdn.net/mhqyr422/article/details/79787518

3,Java發送http get/post請求,調用接口/方法 - 向前爬的蝸牛 - 博客園

https://www.cnblogs.com/wdpnodecodes/p/7807027.html

相關文章
相關標籤/搜索