开发者

Making a HTTPS Post request using XML in Java

I'm trying to use the API from Web Of Knowledge(WoK) to obtain some data. The documentation explain that you have to do POST Requests through HTTPS, sending a XML which contains the queries. But I only get the error 400 form server. (Bad Request)

Here is my code, I found it in Google and I make some fixes for my case.

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开发者_StackOverflow 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();
    }
}


There is something wrong with the XML you are sending. You will have to look at server logs to find out exactly what, as 400 deliberately tells you as little as possible.


You should do it like this. First read the contents of the xml to String and do post using a 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜