/**
* 向指定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;
}
如果參數中是圖片base64格式,注意encode
import java.net.URLEncoder;
String params = "image=" + URLEncoder.encode(imgBase64, "UTF-8") + "&access_token=" + accessToken;