使用Java中的XML创建HTTPS Post请求

时间:2011-09-29 08:45:13

标签: java xml post https request

我正在尝试使用Web Of Knowledge(WoK)中的API来获取一些数据。该文档说明您必须通过HTTPS执行POST请求,并发送包含查询的XML。但我只得到错误400表单服务器。 (错误请求)

这是我的代码,我在谷歌找到了它,我为我的案例做了一些修复。

public static void main(String[] args) throws Exception {



    // Get target URL
    String strURL = /*Here the Server URL*/;

    // Get file to be posted
    String strXMLFilename = "src/main/resources/xml/wosdata.xml";
    File input = new File(strXMLFilename);

    // Prepare HTTP post
    PostMethod post = new PostMethod(strURL);

    // Request content will be retrieved directly
    // from the input stream
    // Per default, the request content needs to be buffered
    // in order to determine its length.
    // Request body buffering can be avoided when
    // content length is explicitly specified
    post.setRequestEntity(new InputStreamRequestEntity(
            new FileInputStream(input), input.length()));

    // Specify content type and encoding
    // If content encoding is not explicitly specified
    // ISO-8859-1 is assumed
    post.setRequestHeader(
            "Content-type", "text/xml; charset=ISO-8859-1");

    // Get HTTP client
    HttpClient httpclient = new HttpClient();



    // Execute request
    try {

        int result = httpclient.executeMethod(post);

        // Display status code
        System.out.println("Response status code: " + result);

        // Display response
        System.out.println("Response body: ");
        System.out.println(post.getResponseBodyAsString());


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

    } finally {
        // Release current connection to the connection pool 
        // once you are done
        post.releaseConnection();
    }
}

2 个答案:

答案 0 :(得分:1)

您发送的XML存在问题。您将不得不查看服务器日志以找出确切的内容,因为400会尽可能少地告诉您。

答案 1 :(得分:0)

你应该这样做。首先将xml的内容读取到String并使用StringRequestEntity进行发布。

// Get file to be posted
String strXMLFilename = "src/main/resources/xml/wosdata.xml";
StringBuilder contents = new StringBuilder();

try {
  BufferedReader input =  new BufferedReader(new FileReader(new File(strXMLFilename)));
  try {
    while (( line = input.readLine()) != null){
      contents.append(line);
      contents.append(System.getProperty("line.separator"));
    }
  }
  finally {
    input.close();
  }



  StringEntity requestEntity = new StringEntity(contents.toString());
  post.setEntity(requestEntity);