I have to make a http request with encrypted query param from one end to another. Say for an example,
String queryParam = "bookName=WingsOfFire&author=AbdulKalam";
String encryptedQueryParam = encrypt(queryParam, encryptionKey);
The final url would be like
domain_name?encryptedQueryParam
On the other end, I would decrypt the query params and obtain the query String. Like
String decryptParam = decrypt(encryptedQueryParam, decryptKey);
Here I'm manually de-serialising my query params at the other end instead of request.getPameter("value").
Is there any other option to handle it in a better way? Any help would be greatly appreciated :-)
Related
I'm trying to get the query parameter client_id from a GET call with a url like this:
https://example.com?client_id=aclient-id¶m2=value2¶m3=value3
I'm getting a null value for clientId when I try to get the query parameter, any ideas why this is happening?
HttpServletRequest httpRequest = (HttpServletRequest) request;
final String clientId = httpRequest.getParameter("client_id");
The other calls like http.getRequestURI() and http.getMethod return the expected values.
Please check what the string value of the client id that is actually being sent to the server. In your example you say clientId in your code you're looking for client_id, while they make semantic sense to humans, those are different values to a computer.
You can also take a peek at all the parameter values in your HttpServletRequest:
httpRequest.getParameterMap()
.entrySet()
.stream()
.forEach(System.out::println);
I’m writing an Android app which collects user information and ultimately stores that in mySQL.
To add a new user, I’m sending _POST data to a PHP script from Android using:
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("id",params.get("id"))
.appendQueryParameter("name",params.get("name"))
.appendQueryParameter("email",params.get("email"));
String query = builder.build().getEncodedQuery();
On the PHP side, I’m receiving the _POST data and inserting to mySQL using:
$id = $_POST["id"];
$name = $_POST["name"];
$email = $_POST["email"];
$query = "INSERT INTO users(id,name,email) VALUES('$id','$name','$email')";
Simple stuff. However, I would also like to bulk add thousands of such records in one shot.
No problem on the Java side: I have an
Arraylist<HashMap<String,String>>
to hold these thousands of ‘rows’ of user data.
However, how can I pass this Arraylist of HashMaps to _POST?
In turn, on the PHP side, how can I dissect the lengthy _POST data (I would imagine breaking down an array) and write to the mySQL database?
I’ve not found a specific example of this on SO, on the Java end or the PHP end.
Thanks to the power of 3.
You could try to use an interchangeable format for that, JSON for example.
Convert a Java hashmap to a JSON object through: new JSONObject(map);
Then you could decode it in PHP, either manually or through an existing function, e.g. json_decode().
Is this what you are looking for?
I have query parameters which are being sent from browser in the following format
sort[0][field]:prodId
sort[0][dir]:asc
How can I retrieve the above parameters in server using #QueryParam?
From chrome console
take:5
skip:0
page:1
pageSize:5
sort[0][field]:prodId
sort[0][dir]:asc
#QueryParam should be obtained from a Query String that is appended to the end of the request URL. Something like
http://host:port/app/something?key1=value2&key2=value2
You could then get value1 and value2 with
#QueryParam("key1") String value1,
#QueryParam("key2") String value2
Now in the title of your post, you use the word "Form". If this is form data you are trying to submit, you should consider some things. When putting the form data in the query String, this is usually done with data that is not sensitive, and used mainly for GET request, where the parameter values are used to help filter in getting the resource. If this is sensitive data that should be stored on the server, you generally want to POST the data as form data in the body of the request, as seen in the answer from your previous post
UPDATE
If you don't know the key names, which is required to use #QueryParam, you can obtain the entire query string from an injected UriInfo. Something like
#GET
#Path("/path/to/resource")
public Response getKendo( #Context UriInfo uriInfo) {
MultivaluedMap params = uriInfo.getQueryParameters();
StringBuilder builder = new StringBuilder();
for (Object key : params.keySet()) {
builder.append(key).append(":")
.append(params.getFirst(key)).append("\n");
}
return Response.ok(builder.toString()).build();
}
getQueryParameters() will return all the keys and values in MultivalueMap
Alternatively, if you know the keys, which are shown in the URL you posted in the comment
test.jsp?take=5&skip=0&page=1&pageSize=5&sort%5B0%5D%5Bfield%5D=prodId&sort%5B0%5D%5Bdir%5D=asc
then you cause just use all those key for the QueryParam, i.e.
public Response getKendo(#QueryParam("take") int take,
#QueryParam("skip") int skip,
#QueryParam("page") int page,
#QueryParam("sort[0][field]") String field...) {
}
All this crazy stuff sort%5B0%5D%5Bfield%5D is just how URL are encoded with special character, but JAX-RS will convert back to their rightful form, ie "sort[0][field]"
In HttpServletRequest, getParameterMap returns a Map of all query string parameters and post data parameters.
Is there a way to get a Map of ONLY query string parameters? I'm trying to avoid using getQueryString and parsing out the values.
You can use request.getQueryString(),if the query string is like
username=james&password=pwd
To get name you can do this
request.getParameter("username");
Contrary to what cularis said there can be both in the parameter map.
The best way I see is to proxy the parameterMap and for each parameter retrieval check if queryString contains "&?<parameterName>=".
Note that parameterName needs to be URL encoded before this check can be made, as Qerub pointed out.
That saves you the parsing and still gives you only URL parameters.
The servlet API lacks this feature because it was created in a time when many believed that the query string and the message body was just two different ways of sending parameters, not realizing that the purposes of the parameters are fundamentally different.
The query string parameters ?foo=bar are a part of the URL because they are involved in identifying a resource (which could be a collection of many resources), like "all persons aged 42":
GET /persons?age=42
The message body parameters in POST or PUT are there to express a modification to the target resource(s). Fx setting a value to the attribute "hair":
PUT /persons?age=42
hair=grey
So it is definitely RESTful to use both query parameters and body parameters at the same time, separated so that you can use them for different purposes. The feature is definitely missing in the Java servlet API.
As the other answers state there is no way getting query string parameters using servlet api.
So, I think the best way to get query parameters is parsing the query string yourself. ( It is more complicated iterating over parameters and checking if query string contains the parameter)
I wrote below code to get query string parameters. Using apache StringUtils and ArrayUtils which supports CSV separated query param values as well.
Example: username=james&username=smith&password=pwd1,pwd2 will return
password : [pwd1, pwd2] (length = 2)
username : [james, smith] (length = 2)
public static Map<String, String[]> getQueryParameters(HttpServletRequest request) throws UnsupportedEncodingException {
Map<String, String[]> queryParameters = new HashMap<>();
String queryString = request.getQueryString();
if (StringUtils.isNotEmpty(queryString)) {
queryString = URLDecoder.decode(queryString, StandardCharsets.UTF_8.toString());
String[] parameters = queryString.split("&");
for (String parameter : parameters) {
String[] keyValuePair = parameter.split("=");
String[] values = queryParameters.get(keyValuePair[0]);
//length is one if no value is available.
values = keyValuePair.length == 1 ? ArrayUtils.add(values, "") :
ArrayUtils.addAll(values, keyValuePair[1].split(",")); //handles CSV separated query param values.
queryParameters.put(keyValuePair[0], values);
}
}
return queryParameters;
}
Java 8
return Collections.list(httpServletRequest.getParameterNames())
.stream()
.collect(Collectors.toMap(parameterName -> parameterName, httpServletRequest::getParameterValues));
I am afraid there is no way to get the query string parameters parsed separately from the post parameters. BTW the fact that such API absent may mean that probably you should check your design. Why are you using query string when sending POST? If you really want to send more data into URL use REST-like convention, e.g. instead of sending
http://mycompany.com/myapp/myservlet?first=11&second=22
say:
http://mycompany.com/myapp/myservlet/11/22
How the best way to handle query strings in Java JSP?
The method request.getQueryString() returns only a strings, how can I get the value of a specific string? Should I parse that string?
thanks
request.getParameter("param-name");
if query string is like
id=12&name=abc
to get name you can do this
request.getParameter("name");