restful風格的http介面呼叫
阿新 • • 發佈:2018-12-23
說明:
引數1:http請求的訪問路徑
引數2:請求方式 post get patch delete
引數3:請求內容,xml或json格式的報文,字串都可以
附程式碼:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; /** * restful介面呼叫工具 */ public class RestfulUtil { /*** 連線hlfront * @param url: * @param param:請求方式 * @param message:報文 * @return */ public static String dealCon(String url, String param, String message) throws IOException { param = param.toUpperCase();// POST DELETE PATCH GET StringBuffer result = new StringBuffer();//返回 URL restServiceURL = newURL(url); HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection(); httpConnection.setDoOutput(true);//允許輸出 httpConnection.setDoInput(true);//允許輸入 httpConnection.setUseCaches(false);//不用快取 httpConnection.setRequestMethod(param); httpConnection.setRequestProperty("Charset", "UTF-8"); httpConnection.setRequestProperty("Accept", "application/json"); // httpConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + UUID.randomUUID().toString()); if("POST".equals(param)){ //傳遞引數 // String input = URLEncoder.encode(message, "UTF-8"); String input = message; OutputStream outputStream = httpConnection.getOutputStream(); outputStream.write(input.getBytes()); outputStream.flush(); } if (httpConnection.getResponseCode() != 200) { throw new RuntimeException( "HTTP "+ param +" Request Failed with Error code : " + httpConnection.getResponseCode()); } BufferedReader responseBuffer = new BufferedReader( new InputStreamReader((httpConnection.getInputStream()))); String output = ""; while ((output = responseBuffer.readLine()) != null) { result.append(output); } httpConnection.disconnect(); return result.toString(); } }