I have an HttpUriRequest instance, is ther开发者_JAVA百科e a way to print all the parameters it contains? For example, I can almost get them like:
HttpUriRequest req = ...;
HttpParams params = req.getParams();
for (int i = 0; i < params.size(); i++) { // ?
println(params.getParam(i); // ?
}
Is there a way to do this?
Thanks
You can simply iterate over all Header fields.
HttpUriRequest req = ...;
.......
Header[] headerFields = request.getAllHeaders();
for(int e = 0; e<header.length; e++){
System.out.println(headerFields[e].getName() + ": " + headerFields[e].getValue());
}
The suggested method params.toString() does not work.
Are you looking for the HTTP parameters or the URI parameters?
The HTTP parameters are things like user-agent, socket buffer size, protocol version, etc.
The URI parameters are the client values that get passed as part of the request, e.g.
?param1=value1¶m2=value2
If you're looking for the URI parameters, try something like this:
List<String> uriParams = Arrays.asList(request.getURI().getQuery().split("&"));
But if you do want the raw HTTP params, it's a little more complicated because not all implementations of HttpParams supports getNames()
. You'd have to do something like this:
HttpParamsNames params = (HttpParamsNames)request.getParams();
Set<String> names;
if (params instanceof ClientParamsStack) {
names = new HashSet<>();
// Sorted by priority, see ClientParamsStack
ClientParamsStack cps = (ClientParamsStack)params;
if (cps.getApplicationParams() != null) {
names.addAll(((HttpParamsNames)cps.getApplicationParams()).getNames());
}
if (cps.getClientParams() != null) {
names.addAll(((HttpParamsNames)cps.getClientParams()).getNames());
}
if (cps.getRequestParams() != null) {
names.addAll(((HttpParamsNames)cps.getRequestParams()).getNames());
}
if (cps.getOverrideParams() != null) {
names.addAll(((HttpParamsNames)cps.getOverrideParams()).getNames());
}
} else {
names = params.getNames();
}
for (String name : names) {
System.out.println(name + ": " + request.getParams().getParameter(name));
}
HttpUriRequest extends HttpMessage, which has getAllHeaders(), getParams() etc.
Take a look here: http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/index.html, search for HttpMessage
You could create a work around by casting it to BasicHttpParams object.
BasicHttpParams basicParams = (BasicHttpParams) params;
This give you access to getNames()
which contains a HashSet<String>
of the parameters
You can then iterate through it printing out the parameter name alongside it's value.
See https://stackoverflow.com/a/57600124/5622596 for possible solution
精彩评论