java--向指定URL傳送POST方法的請求 Content-Type=application/x-www-form-urlencoded
阿新 • • 發佈:2020-12-24
/** * 向指定URL傳送POST方法的請求 Content-Type=application/x-www-form-urlencoded * * @param targetUrl 傳送請求的URL * @param params 請求引數,請求引數應該是name1=value1&name2=value2的形式。 * @return JSONObject 返回的JSON資料 */ public static JSONObject postFormUrlEncoded(String targetUrl, String params) { HttpURLConnection urlConnection = null; try { URL url = new URL(targetUrl.trim()); urlConnection = (HttpURLConnection) url.openConnection(); // 設定請求方式 urlConnection.setRequestMethod("POST"); // 設定資料型別 urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 設定允許輸入輸出 urlConnection.setDoOutput(true); urlConnection.setDoInput(true); // 設定不用快取 urlConnection.setUseCaches(false); urlConnection.connect(); PrintWriter out = new PrintWriter(new OutputStreamWriter(urlConnection.getOutputStream(), StandardCharsets.UTF_8)); // 寫入傳遞引數,格式為a=b&c=d out.print(params); out.flush(); int resultCode = urlConnection.getResponseCode(); if (HttpURLConnection.HTTP_OK == resultCode) { StringBuffer stringBuffer = new StringBuffer(); String readLine; BufferedReader responseReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), StandardCharsets.UTF_8)); while ((readLine = responseReader.readLine()) != null) { stringBuffer.append(readLine); } responseReader.close(); return JSONObject.parseObject(stringBuffer.toString()); } out.close(); } catch (Exception e) { return null; } finally { if (urlConnection != null) { urlConnection.disconnect(); } } return null; }