HttpRequest.BodyPublishers.ofString(jsonasstring) does not put anything in the POST request - java

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?

Related

how do I use JAX-WS Entity.json

I am trying to request a json file from openrouteservice.org and I dont know that much about json so I used the code exmaple on their site https://openrouteservice.org/dev/#/api-docs/v2/directions/{profile}/json/post in java. I replaced the coordinates with my list of coordinates(Double[]), but it says i`d need other tokens. Heres the code:
Client client = ClientBuilder.newClient();
Entity<String> payload = Entity.json({"coordinates":[list]});
Response response = client.target("https://api.openrouteservice.org/v2/directions/foot-walking/json")
.request()
.header("Authorization", "***")
.header("Accept", "application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8")
.header("Content-Type", "application/json; charset=utf-8")
.post(payload);
System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
}
In the line
Entity<String> payload = Entity.json({"coordinates":[list]});
it says illegal start of expression in the .json() but I couldnt find how to use it properly, even on the official oracle site I didnt manage to understand how to solve it. I know its probably a very stupid question but thank you very much for erveryone who can help me

Send the API Headers in Rest Assured using java

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 :)

Post multipart file and JSON in Rest Assured

I need to send a video file and JSON object in Rest Assured post call.
Structure is like the following:
{ "sample" : {
"name" : "sample-name",
"kind" : "upload",
"video_file" : multipart file here } }
So I did like the following
Code:
given()
.header("Accept", "application/json")
.header(auth)
.config(rConfig)
.body(body)
.multiPart("sample[video_file]", new File("path"), "video/mp4")
.formParam("sample[name]", "Video Upload")
.formParam("sample[kind]", "upload")
.log().all().
expect()
.statusCode(expectedStatusCode)
.post(url);
I can't use application/JSON while using multipart in Rest Assured. I explicitly hardcoded the value in the form param and sent the media file in multipart and now it is working fine.
How can I send all the form param data in a single inner object.
You can do this by using RequestSpecBuilder. It supports all the request parameters and you can easily create multipart request.
Sample code taken from https://github.com/rest-assured/rest-assured/wiki/Usage
RequestSpecBuilder builder = new RequestSpecBuilder();
builder.addParam("parameter1", "parameterValue");
builder.addHeader("header1", "headerValue");
RequestSpecification requestSpec = builder.build();
given().
spec(requestSpec).
param("parameter2", "paramValue").
when().
get("/something").
then().
body("x.y.z", equalTo("something"));
Thanks for your response rohit. I was post this question for handling inner object with formParams. I've completed by creating a Hash Map for formParams. Because formParams method of rest assured can accept Hash map.
Form params map creation:
private static Map<String, String> createFormParamsMap(VideoTagInput videoTag) {
Map<String, String> formParams = new HashMap<>();
formParams.put(createFormParamKey("name"), "name");
formParams.put(createFormParamKey("kind"), "kind");
return formParams;
}
private static String createFormParamKey(String paramKey) {
return "sample[" + paramKey + "]";
// output is like "sample[name]" - I'm forming inner object here for my purpose.
}
Finally send the map to Rest Assured post call function
given()
.header("Accept", "application/json")
.header(auth)
.config(rConfig)
.multiPart("sample[video_file]", new File("path"), "video/mp4")
.formParams(requestParamsMap) // requestParamsMap here.
.log().all().
expect()
.statusCode(expectedStatusCode)
.post(url);
Your approach is definitely not standard.
You cannot have a multipart request and a JSON body, you need to pick one over the 2 approaches: multipart/form-data or application/json request.
The standard way is to have a multipart request with a "json" param containing the serialized JSON payload, and a "file" param with the multipart file.
given()
.contentType(MediaType.MULTIPART_FORM_DATA_VALUE)
.multiPart(file)
.param("json", "{\"sample\":{\"name\":\"sample- name\",\"kind\":\"upload\",\"video_file\":<this is not needed>}}")
But this involves changing your server-side logic.
If you cannot change your server-side logic, you need to serialize your file as (for instance as an array of bytes, or as base64 string) to be set as video_file in your JSON payload. In which case you'll have an application/json content type request, not a 'multipart/form-data'.

Java : How to handle POST request without form?

I'm sending a http post request from javascript, with some json data.
Javascript
var data = {text : "I neeed to store this string in database"}
var xhr= new XMLHttpRequest();
xhr.open("POST","http://localhost:9000/postJson" , true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send(data);
xhr.setRequestHeader("Connection", "close");
//Also, I've tried a jquery POST
//$.post('postJson', {'data=' : JSON.stringify(data)});
//But this doesn't make a request at all. What am I messing up here?
Route
POST /postJson controllers.Application.postJson()
Controller
public static Result postJson(){
//What should I write here to get the data
//I've tried the below but values is showing null
RequestBody rb=request().body();
final Map<String,String[]> values=rb.asFormUrlEncoded();
}
What is the way to parse the POST request body?
Much thanks!
Retreive the request body directly as JSON... no need to complicate your life.
public static Result postJson() {
JsonNode rb = request().body().asJson();
//manipulate the result
String textForDBInsertion = rb.get("text").asText(); //retreives the value for the text key as String
Logger.debug("text for insertion: " + textForDBInsertion
+ "JSON from request: " + rb);
return ok(rb);
}
Also, I recommend you use the AdvancedRestClient Chrome plugin for testing. This way you can eliminate from the equation client-side code errors.
Cheers!

How to get response from restlet ClientResource?

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");
}

Categories