傳送HTTP POST請求工具類
阿新 • • 發佈:2018-12-19
package com.example.demo; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class HttpUtilTest { /** * @作用 使用urlconnection * @param url * @param Params * @return * @throws IOException */ public static String sendPost(String url,String Params)throws IOException{ OutputStreamWriter out = null; BufferedReader reader = null; String response=""; try { URL httpUrl = null; //HTTP URL類 用這個類來建立連線 //建立URL httpUrl = new URL(url); //建立連線 HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("connection", "keep-alive"); conn.setUseCaches(false);//設定不要快取 conn.setInstanceFollowRedirects(true); conn.setDoOutput(true); conn.setDoInput(true); conn.connect(); //POST請求 out = new OutputStreamWriter( conn.getOutputStream()); out.write(Params); out.flush(); //讀取響應 reader = new BufferedReader(new InputStreamReader( conn.getInputStream())); String lines; while ((lines = reader.readLine()) != null) { lines = new String(lines.getBytes(), "utf-8"); response+=lines; } reader.close(); // 斷開連線 conn.disconnect(); } catch (Exception e) { System.out.println("傳送 POST 請求出現異常!"+e); e.printStackTrace(); } //使用finally塊來關閉輸出流、輸入流 finally{ try{ if(out!=null){ out.close(); } if(reader!=null){ reader.close(); } } catch(IOException ex){ ex.printStackTrace(); } } return response; } }