编辑:我如何发送带有参数和表单数据的发帖请求,例如JAVA中的此邮递员屏幕截图?

时间:2018-07-13 20:36:27

标签: java rest post request

POSTMAN Screenshot

我正在尝试发送POST请求以获取注释,但是在Java中它不能与邮递员一起使用,但是它在Java中不起作用。

我收到403禁止的错误,但是在邮递员上,它可以检索我需要的数据。

这是我试图用来复制行为的Java代码。

String targetUrl = YOUTBE_COMMENTS_AJAX_URL;
    String urlParameters = "action_load_comments=1&order_by_time=True&filter=jBjXVrS8nXs";
    String updatedURL = targetUrl + "?" + urlParameters;
    URL url = null;
    InputStream stream = null;
    HttpURLConnection urlConnection = null;
    try {
        url = new URL(updatedURL);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("content-type", "multipart/form-data");
        urlConnection.setRequestProperty("user-agent", "USER_AGENT");
        urlConnection.setDoOutput(true);

        String data = URLEncoder.encode("video_id", "UTF-8")
                + "=" + URLEncoder.encode(youtubeId, "UTF-8");

        data += "&" + URLEncoder.encode("session_token", "UTF-8") + "="
                + URLEncoder.encode(xsrfToken, "UTF-8");

        data += "&" + URLEncoder.encode("page_token", "UTF-8") + "="
                + URLEncoder.encode(pageToken, "UTF-8");
        urlConnection.connect();

        OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
        wr.write(data);
        wr.flush();

        stream = urlConnection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"), 8);
        String result = reader.readLine();
        return result;

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return null;

Here's an example of what postman is sending in their headers

1 个答案:

答案 0 :(得分:0)

似乎您的问题在这里(请参阅嵌入式注释):

DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(urlParameters); 
// you wrote your URL parameters into Body
wr.flush();
wr.close(); 
//You closed your body and told server - you are done with request
conn.getOutputStream().write(postDataBytes); 
// you wrote data into closed stream - server does not care about it anymore. 
  • 打开时,您必须将urlParameters直接附加到URL
  • 然后,您必须像执行操作一样将表单数据写入主体: conn.getOutputStream().write(postDataBytes);
  • 然后关闭输出流