I try make request using client library javax.ws.rs
I'm trying to add a parameter name containing characters [ and ] to query parameters, for encdoded special characters i am used URLEncoder.encode(). But after the request, the response contains data without this parameter, the server ignored this request parameter. I made a request on the command line using "curl" on purpose with an error in this parameter and got the same result as from the request in the application. The error is clearly in the encoded parameter name, but I don’t understand how to correctly add parameters containing special characters.
The Code:
WebTarget webTarget = new Client().target(uri);
String key = "filters[Time].Start";
key = URLEncoder.encode(key,StandardCharsets.UTF_8.toString());
String value = "2022-08-27+17:00:00";
value = URLEncoder.encode(value,StandardCharsets.UTF_8.toString());
System.out.println(key + " " + value);
webTarget = webTarget.queryParam("per_page","10");
webTarget = webTarget.queryParam(key,value);
webTarget = webTarget.queryParam("order_by","time");
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
Response response = invocationBuilder.get();
Result sout : filters%5BTime%5D.Start 2022-08-27%2B17%3A00%3A00
By advise #cyberbrain, i did checked my request in server by help 'tcpdump' utilite with key '-A'.
I did request by curl and after by my java application and compare data.
In my case problems was in value parametrs, my value equels "2022-08-27+17:00:00". After add in queryparametr this symbol '+' encoded to code '%2B' and this don't like my server. I just replaced symbol '+' to symbol space (code %20) in value ("2022-08-27 17:00:00"). After that i geted correct data from my server
Related
I do have get request over http from an angular based client side which expects as an answer an array of bytes from a java server.
angular.ts
downloadDocument(documentId: string) {
const params = new HttpParams().set('docId', documentId);
return this.httpClient.get<any>(`/downloadpdf/`,
{ params: params});
}
controller.java
#GetMapping("/downloadpdf")
public String downloadDocument(#RequestParam("docId") final String docId) {
String response = (new String(getBytesArray(docId)));
// getBytesArray returns a byte[]
// response correctly computed
return response;
}
Parsing error is encountered while transmitting over http:
"HttpErrorResponse":
message: 'Http failure during parsing for http://localhost...'
error: 'error: SyntaxError: Unexpected token % in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad'
Any ideas why this is happening?
It's happening because you call the overload of get() that takes a generic parameter:
this.httpClient.get<any>(...)
This overload sets the response type to JSON, thus telling the HttpClient to parse the response body to JSON and to returned the generated object or array. Since you do not want to receive JSON, you must use another overload.
The documentation is your friend.
If you want to receive a Blob, for example, you would use the second overload, documented as returning an Observable<Blob>, and expecting options with responseType: 'blob'.
API URL : https://davids-restaurant.herokuapp.com/menu_items.json?category=C
I'm trying to retrieve name property of ID 913 from the above rest API
Please find my code below
String URL = "https://davids-restaurant.herokuapp.com/menu_items.json?category=C";
Response res = RestAssured.get(URL);
JsonPath jsonPathEvaluator = res.jsonPath();
System.out.println(jsonPathEvaluator.get("$..menu_items[?(#id == 913)].description"));
Error Message
java.lang.IllegalArgumentException: Invalid JSON expression:
Script1.groovy: 1: expecting EOF, found '[' # line 1, column 40.
$..menu_items[?(#id == 913)].description
^
I tried this which works but I donot want to query with index but I want to query with ID
System.out.println(jsonPathEvaluator.get("menu_items[1].description"));
You can use Groovy filters to get the result. Have a look at this code.
io.restassured.response Response;
// response= Get the API response
List<String> namesList = from(response.asString()).getList("menu_items.findAll { it.id == 913 }.name");
Here I have created a list but you can find single item by using 'item.find'.
The following code produces a string that has question marks as the display name when I insert an Iranian address(?????, ???????). However if I put the same url into my browser, it returns Tehran, Iran instead of question marks. I know that it has something to do with encoding but how do I get the English text as the browser returns in my java application?
String rawAddress = "Tehran";
String address = URLEncoder.encode(rawAddress, "utf-8");
String geocodeURL = "http://nominatim.openstreetmap.org/search?format=json&limit=1&polygon=0&addressdetails=0&email=myemail#gmail.com&languagecodes=en&q=";
String formattedUrl = geocodeURL + address;
URL theGeocodeUrl = new URL(formattedUrl);
System.out.println("HERE " +theGeocodeUrl.toString());
InputStream is = theGeocodeUrl.openStream();
final ObjectMapper mapper = new ObjectMapper();
final List<Object> dealData = mapper.readValue(is, List.class);
System.out.println(dealData.get(0).toString());
I tried the following code but it produced this: تهران, �ايران‎ for the display name which should be Tehran, Iran.
System.out.println(new String(dealData.get(0).toString().getBytes("UTF-8")));
Use "accept-language" in the URL parameter for Nominatim to specify the preferred language of Nominatim's results, overriding whatever default the HTTP header may set. From the documentation:
accept-language= <browser language string>
Preferred language order for showing search results, overrides the
value specified in the "Accept-Language" HTTP header. Either uses
standard rfc2616 accept-language string or a simple comma separated
list of language codes.
I'm trying to access a REST webservice from SalesForce from my java application.
I'm using Jersey to make the webservice call.
private String getRegisterId(String registerName, String accessToken) throws JSONException, BusinessException {
ClientConfig config = new DefaultClientConfig();
config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(config);
WebResource wr = client.resource(salesforeceUrl + "/data/v31.0/query");
JSONObject register = wr //
.queryParam("q", "SELECT+Id+FROM+HealthData_Register__c+WHERE+name+=+'" + registerName + "'+AND+IsDeleted+=+false") //
.header(HttpHeaders.AUTHORIZATION.getValue(), "Bearer " + accessToken) //
.get(JSONObject.class);
JSONArray records = register.getJSONArray("records");
return records.getJSONObject(0).getString("Id");
}
The problem I have is that Jersey is so nice that it changes the + symbol to %2B and the + symbol to %3D for my queryParam but SalesForce doesn't like this.
It also does this for the header. If my accessToken contains a special character I will get an 401 (UNAUTHORIZED) response.
Is there a way to ask Jersey to not make special symbols url-safe?
Since it's a GET request it's correct that the query params are url-encoded.
Why do you put the symbol + instead of spaces in the query? Did you try putting just the spaces? Is really the server expecting a + symbol instead of spaces?
I am trying to get the access_token from facebook. First I redirect to facebook using an url as the following
https://graph.facebook.com/oauth/authorize?type=user_agent&client_id=7316713919&redirect_uri=http://whomakescoffee.com:8080/app/welcome.jsf&scope=publish_stream
Then I have a listener that gets the url.
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletRequest request =
(HttpServletRequest) fc.getExternalContext().getRequest();
String url = request.getRequestURL().toString();
if (url.contains("access_token")) {
int indexOfEqualsSign = url.indexOf("=");
int indexOfAndSign = url.indexOf("&");
accessToken = url.substring(indexOfEqualsSign + 1, indexOfAndSign);
handleFacebookLogin(accessToken, fc);
}
But it never gets inside the if..
How do I retrieve the parameter when it comes after a # instead of a usual parameter after ?.
The url looks something like
http://benbiddington.wordpress.com/#access_token=
116122545078207|
2.1vGZASUSFMHeMVgQ_9P60Q__.3600.1272535200-500880518|
QXlU1XfJR1mMagHLPtaMjJzFZp4
The URL is incorrectly encoded. It's XML-escaped instead of URL-encoded. The # is a reserved character in URL's which represents the client-side fragment which is never sent back to the server side.
The URL should more look like this:
https://graph.facebook.com/oauth/authorize?type=user_agent&client_id=7316713919&redirect_uri=http%3a%2f%2fwhomakescoffee.com%3a8080%2fapp%2fwelcome.jsf%26scope%3dpublish_stream
You can use java.net.URLEncoder for this.