且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从XML http请求中读取XML?

更新时间:2023-11-14 22:29:28

我通过将其更改为POST请求解决了问题(和浏览器一样)。我还包括与该请求相关联的表单数据,如图所示。

I solved the issue by changing it to a POST request (same as what the browser did). I also included the form data associated with that request as shown in the pictures up there.

private StringBuffer sendPost() {

    StringBuffer response = new StringBuffer();
    String url = "https://example.com/snowbound/AjaxServlet";
    final String CONTENT_LENGTH = "131";
    final String CONTENT_TYPE = "application/x-www-form-urlencoded";
    final String ACCEPT_LANGUAGE = "en-US,en;q=0.8";

    try {
        //create http connection
        URL obj = new URL(url);
        HttpsURLConnection connection = (HttpsURLConnection) obj.openConnection();

        //add request header
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestProperty("Accept-Language", ACCEPT_LANGUAGE);
        connection.setRequestProperty("Content-Type", CONTENT_TYPE);
        connection.setRequestProperty("Content-Length", CONTENT_LENGTH);

        DataOutputStream output = new DataOutputStream(connection.getOutputStream());

        //form data
        String content = "documentId=3896&action=getAnnotationModel&annotationLayer=1&pageCount=1&pageIndex=0";

        //write output stream and close output stream
        output.writeBytes(content);
        output.flush();
        output.close();

        //read in the response data
        BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        while((inputLine = input.readLine()) != null) {
            response.append(inputLine.toString());
        }

        //close input stream
        input.close();

        //print out content
        int responseCode = connection.getResponseCode();
        System.out.println("response code: " + responseCode);
        System.out.println("respone is: " + response);

    } catch (MalformedURLException e) {
        e.printStackTrace();

    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;
}