java--向指定URL发送POST方法的请求 Content-Type=application/x-www-form-urlencoded


    /**
     * 向指定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;


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM