java如何实现post请求url,并使用Content-Type=application/x-www-form-urlencoded呢?

杨采妮 Java经验 2022-05-25 22:41:56 15532 1
下文笔者讲述post请求url的方法分享,如下所示
 
    /**
     * 向指定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;
    }
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: http://www.Java265.com/JavaJingYan/202205/16534897553513.html

最近发表

热门文章

好文推荐

Java265.com

//www.java265.com

站长统计|USA-001

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

Honor accompaniments