HttpRequestBase - 如何打印请求及其所有数据
我正在使用HttpRequestBase,我想在使用之前将请求完全记录到日志文件中。
默认值为String仅返回请求行,我想打印所有标头,参数,请求正文等...
有没有办法做到这一点?
我正在使用HttpRequestBase,我想在使用之前将请求完全记录到日志文件中。
默认值为String仅返回请求行,我想打印所有标头,参数,请求正文等...
有没有办法做到这一点?
对象 (, 等) 包含有关标头、参数的信息,实现类包含正文,但它实际上并未序列化为 .当实际发送请求时,就会发生这种情况。HttpRequestBase
HttpGet
HttpPost
String
HttpClient
您可以使用 http 组件日志记录配置。
或者,您可以调用适当的方法并自己动手。
HttpRequestBase base = new HttpGet("www.google.com");
Header[] headers = base.getAllHeaders();
// iterate and print
对于主体,您需要强制转换为实现类并获取 ,如果它有。HttpEntity
HttpEntity entity = ((HttpPost)base).getEntity(); // example
并打印它(其内容)。注意:这可能会消耗实体。InputStream
完整示例
HttpPost post = new HttpPost("www.google.com");
post.setHeader(new BasicHeader("User-Agent", "random client"));
HttpEntity entity = new StringEntity("yellaworld");
post.setEntity(entity);
Header[] headers = post.getAllHeaders();
String content = EntityUtils.toString(entity);
System.out.println(post.toString());
for (Header header : headers) {
System.out.println(header.getName() + ": " + header.getValue());
}
System.out.println();
System.out.println(content);
指纹
POST www.google.com HTTP/1.1
User-Agent: random client
yellaworld
这有效
private void printRequest() {
System.out.println("receive " + httpRequest.getMethod() +" notification for "+ httpRequest.getRequestURI());
System.out.println(" \n\n Headers");
Enumeration headerNames = httpRequest.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = (String)headerNames.nextElement();
System.out.println(headerName + " = " + httpRequest.getHeader(headerName));
}
System.out.println("\n\nParameters");
Enumeration params = httpRequest.getParameterNames();
while(params.hasMoreElements()){
String paramName = (String)params.nextElement();
System.out.println(paramName + " = " + httpRequest.getParameter(paramName));
}
System.out.println("\n\n Row data");
System.out.println(extractPostRequestBody(httpRequest));
}
static String extractPostRequestBody(HttpServletRequest request) {
if ("POST".equalsIgnoreCase(request.getMethod())) {
Scanner s = null;
try {
s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
} catch (IOException e) {
e.printStackTrace();
}
return s.hasNext() ? s.next() : "";
}
return "";
}