I'm trying to do a POST call by adding "Content-Encoding" Header to the request. Here is my code
Invocation.Builder builder =
webTarget.request(MediaType.APPLICATION_XML).header("Content-Encoding",
"xml").accept(MediaType.TEXT_PLAIN);
String xmlRequest=
buildMerchantPreferencesRequest(accountNumber,emailID,thresholdValue);
response = header.post(Entity.xml(xmlRequest.toString()));
String value = response.readEntity(String.class);
Thread.sleep(5000);
System.out.println("Service STATUS : "+response.getStatus());
System.out.println("Response message : "+value);
Returns Response as follows :
STATUS : 400
Response message : Request for service PreferencesLifecycle version 1.0-
211.0-35789706 is missing Content-Encoding header
Response says "Content-Encoding" header is missing.
Can anyone help me here, and point me to the right way of doing it?
Response response;
String xmlRequest= buildMerchantNBPreferencesRequest(accountNumber,emailID,thresholdValue);
Variant variant = new Variant(MediaType.APPLICATION_XML_TYPE, null, null, "XML");
Invocation.Builder builder = merchantPreferencesClient.request().header("Content-Encoding", "XML").property("Content-Encoding", "XML");
Invocation invocation = builder.header("Content-Encoding", "XML").buildPost(Entity.entity(xmlRequest, variant));
response = invocation.invoke();
Related
i need to insert # symbol in the api request. official documentation transforms https://api.brawlstars.com/v1/players/#2JV9PR99Y to https://api.brawlstars.com/v1/players/%232JV9PR99Y.
so if i send request with %23 i will get 404 Not Found: [{"reason":"notFound","message":"Not found with tag %232JV9PR99Y"}] but with postman i can send requests with %23 replace #. if if send request with # it just returns null json body.
my code:
public Player showPlayerInfo(String playerTag) {
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization","Bearer " + bearerToken);
HttpEntity<String> request = new HttpEntity<String>(headers);
String url = "https://api.brawlstars.com/v1/players/%232JV9PR99Y"; // testing
System.out.println(url);
ResponseEntity<Player> response = restTemplate.exchange(url, HttpMethod.GET, request, Player.class);
return response.getBody();
}
tried to transform link using java.lang URI and URL. also just delete # or %23 from url. api doesnt get it
So I am trying to make a HTTP request to get access token and refresh token using following java code.
String url = "https://oauth2.googleapis.com/token?";
Map<String, String> parameters = new HashMap<>();
parameters.put("code", "4%2******");
parameters.put("client_id", "*****");
parameters.put("client_secret", "*****");
parameters.put("redirect_uri", "http://localhost");
parameters.put("grant_type","authorization_code");
parameters.put("access_type","offline");
String form = parameters.keySet().stream()
.map(key -> key + "=" + URLEncoder.encode(parameters.get(key), StandardCharsets.UTF_8))
.collect(Collectors.joining("&"));
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url))
.headers("Content-Type", "application/json")
.POST(BodyPublishers.ofString(form)).build();
HttpResponse<?> response = client.send(request, BodyHandlers.ofString());
System.out.println(response.statusCode() + response.body().toString());
But using this code gives the following error,
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unexpected token.\ncode=4%2****\n^",
"status": "INVALID_ARGUMENT"
}
}
What is the mistake that I have done here and should rectify in order to get proper results?
You are sending application/x-www-form-urlencoded data format but according to the response message you should send json. Try to change definition of form:
String form = new ObjectMapper().writeValueAsString(parameters);
I'm trying to make a POST request with custom headers and json as string on body
Here's my code
HttpRequest request2 = HttpRequest.newBuilder()
.uri(URI.create(POSTS_API_URL))
.headers("accept", "text/plain; charset=UTF-8", "XF-Api-Key", "MYAPIKEY")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
System.out.println(request2); //result : https://******.fr/api/auth/ POST
System.out.println(request2.headers()); //result : java.net.http.HttpHeaders#8e33ff08 { {accept=[text/plain; charset=UTF-8], XF-Api-Key=[MYAPIKEY]} }
HttpResponse<String> response2 = client.send(request2, HttpResponse.BodyHandlers.ofString());
// print status code
System.out.println(response2.statusCode()); //400
// print json code
System.out.println(json); //{"login":"LunaLune","password":"***********"}
// print response body
System.out.println(response2.body()); //mandatory input missing : login, password
And my json String
String json = "{" +
"\"login\":\"LunaLune\"," +
"\"password\":\"*********\"" +
"}";
But when I print the request I get : https://*******.fr/api/auth/ POST
the POST request is empty
I googled many forums, code examples ect... but I see that my code where correct according many examples I seen.
So if someone know what is my problem ?
Thanks in advance !
You need to set "Content-Type" as "application/json" in the request header.
See: Which JSON content type do I use?
API Headers have two parameter Content-Type=application/json and also accesstoken = "some_token"
I trying to automate the API using Rest assured but not successful.
Below is the code
RestAssured.baseURI = prop.getProperty("serviceurl1");
//2. define the http request:
RequestSpecification httpRequest = RestAssured.given()
.filter(new ResponseLoggingFilter())
.filter(new RequestLoggingFilter());
JSONObject requestParams = new JSONObject();
requestParams.put("longitude", eLongitude);
requestParams.put("latitude", eLaititude);
requestParams.put("country", eCity);
httpRequest.headers("Content-Type", "application/json");
httpRequest.headers("accesstoken", "some_token.");
httpRequest.body(requestParams.toJSONString());
int statusCode = response.getStatusCode();
System.out.println("the status code is: "+ statusCode);
Assert.assertEquals(statusCode, TestUtil.RESPONSE_CODE_200);
System.out.println("the status line is: "+ response.getStatusLine());
//6. get the headers:
Headers headers = response.getHeaders();
System.out.println(headers);
String contentType = response.getHeader("Content-Type");
System.out.println("the value of content-type header is: "+ contentType);
String contentLength = response.getHeader("Content-Length");
System.out.println("the value of Content-Length header is: "+ contentLength);
Getting error message as "Provide Application Token" and 404 error code display.
Your httpRequest.headers("accesstoken", "kggkgkgkgketdfgxgcccvcdftfty."); is wrong. It should be:
httpRequest.headers("Authorization", "Bearer "+token);
can you try this once
Response resp = given().when().contentType(ContentType.JSON).header("accesstoken", "token").body(body).put("url");
You can pass the HashMap as body
These are the issues I can think of
This might be an internal API and it is expecting "Provide Application Token" and not the "accesstoken"
The error code you are getting is 404. So either the service is down or the URL you are using is not correct.
Hope this helps :)
This may be easy one, but I am confused.
I am trying to do HTTP POST on a server using Android Restlet, and read the reply returned from the server.
I created form using:
Form form = new Form
form.add("msg" ,"This is my message");
Now, I have clientResource as follows:
ClientResource clientResource = new ClientResource("www.example.com/my-http-post-url/");
Now, I am doing HTTP Post as:
Representation response=null;
try{
response= clientResource.post(form.getWebRepresentation(null));
System.out.println("Got response !! , response : " + response.getText());
System.out.println( "Got Context: " + clientResource.getContext() );
System.out.println( "Got Response: " + clientResource.getResponse());
System.out.println( "Got Resonse Attribute : " + clientResource.getResponseAttributes() );
System.out.println( "Got Resonse Entity: " + clientResource.getResponseEntity() );
}catch(Exception e){
e.printStackTrace();
}
I found out that the code is going inside try, but its printing :
I/org.restlet( 493): Starting the default HTTP client
I/System.out( 493): Got response !! , response : null
I/System.out( 493): Got Context: null
I/System.out( 493): Got Response: HTTP/1.1 - OK (200) - OK
I/System.out( 493): Got Resonse Attribute : {org.restlet.http.headers=[(Date,Sun, 22 Jul 2012 22:14:03 GMT), (Server,WSGIServer/0.1 Python/2.7.1+), (Vary,Authorization), (Content-Type,application/json; charset=utf-8)]}
I/System.out( 493): Got Resonse Entity: [application/json,UTF-8]
I tried sniffing the data, to see if the server is replying or not, I am confident that server is sending the response content.
Can anyone tell me, how can I find out the response content send by the server?
You're using client-side support of Restlet the right way. The response content should be contained within the response representation...
The first step is to call your REST service outside Android to see the exact response content. Can you try to do this using restclient (http://code.google.com/p/rest-client/) or curl?
Thierry
Try something like this:
I have something similar to this right now:
ClientResource clientResource = new ClientResource(url);
Request request = new Request(Method.POST, url);
clientResource.setRequest(request);
Form form = new Form();
form.set("foo", "barValue");
org.restlet.representation.Representation response = clientResource.post(form, MediaType.APPLICATION_JSON);
Representation responseEntity = clientResource.getResponseEntity();
JsonRepresentation jsonRepresentation = new JsonRepresentation(responseEntity);
JSONObject jsonObject = jsonRepresentation.getJsonObject();
String[] names = JSONObject.getNames(jsonObject);
if (jsonObject.has("errorString"))
{
String error = jsonObject.optString("errorString");
}