如何通过java提取Http Post请求中发送的xml?

时间:2014-09-01 07:49:14

标签: java xml http https

我在java中发出一个http post请求,我需要查看请求中发送的xml。 有没有办法在java中看到xml?请提供打印xml发送请求的方法。

java中的示例代码:

public static void main(String[] args) {
    // TODO Auto-generated method stub
       HttpClient cl = new HttpClient();
       PostMethod postMethod = new PostMethod("***URL***");

       NameValuePair[] params = {
       new NameValuePair("dealerId", "***sampleDealerId***"), 
       new NameValuePair("queryId", "***sampleQueryId***") 
       };

       postMethod.setRequestBody(params);
       cl.getParams().setAuthenticationPreemptive(true);
       Credentials defaultCreds = new UsernamePasswordCredentials("***user***",    "***password***");
       cl.getState().setCredentials(AuthScope.ANY, defaultCreds);

       try { 
           try {
             cl.executeMethod(postMethod);
          }
           catch (IOException e) {
             e.printStackTrace();
          }
          BufferedReader br;

          try { 
            System.out.println(postMethod.getStatusCode()); 
            System.out.println(postMethod.getStatusText());
            br = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream()),256);
                 String line;
                 char[] chars = new char[256];
                 while (br.read(chars) != -1) {
                    System.out.println(chars);
                    chars = new char[256];
                 }
          }
          catch (IOException e) {
             e.printStackTrace();
          }
       }
       finally {
        postMethod.releaseConnection();
       }

}

1 个答案:

答案 0 :(得分:0)

设置以下日志记录参数应该能够记录完整的连线内容(应该包括您正在发送的 XML )和上下文。它适用于 Commons Logging 界面。

  

-Dorg.apache.commons.logging.Log = org.apache.commons.logging.impl.SimpleLog   -Dorg.apache.commons.logging.simplelog.showdatetime =真   -Dorg.apache.commons.logging.simplelog.log.org.apache.http = DEBUG

log4j 的相同级别的调试:

  

log4j.rootLogger = INFO,stdout

     

log4j.appender.stdout = org.apache.log4j.ConsoleAppender   log4j.appender.stdout.layout = org.apache.log4j.PatternLayout   log4j.appender.stdout.layout.ConversionPattern =%5p [%c]%m%n

     

log4j.logger.org.apache.http = DEBUG

More info

根据OP的评论进行编辑:

上面的链接显示了完整的示例。这取决于您正在使用的日志框架。例如,如果您使用 log4j (一种非常常见的日志记录选择),则应使用指定的 log4j 创建 log4j.properties 文件配置参数(我在上面指定的第二个块)。

日志设置生效后,您的代码中不需要明确打印任何内容。假设正确的设置到位,Apache HTTP代码中的现有调试日志记录应记录响应/请求以及其他内容。