Java : How to handle POST request without form? - java

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!

Related

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

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?

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'.

AngularJS $http get return null status 0

I'm trying to create $http get request to fetch some json data generated by my web service, but it returns null error. However, the $http request works fine when I use this sample url instead (it returns json string too)
This is my angular code :
angular.module('ionicApp', ['ionic'])
.controller('ListCtrl', function ($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http.get("http://localhost:8080/InventoryCtrl_Service/webresources/IVC_Service/GetUserList")
.then(function(response) {
console.log("success ");
},
function(response) {
console.log("Error : " + response.data + " Status : " + response.status);
}
});
This is my web service code :
#GET
#Path("/GetUserList")
#Produces("application/json")
public Response GetUserList() throws SQLException {
net.sf.json.JSONObject json = new net.sf.json.JSONObject();
JSONObject obj1 = new JSONObject();
JSONObject obj2 = new JSONObject();
JSONObject outerObject = new JSONObject();
JSONArray arr = new JSONArray();
obj1.put("Name", "Sara");
obj2.put("Name","David");
arr.add(obj1);
arr.add(obj2);
outerObject.put("records", arr);
return Response.status(200).entity(outerObject.toString()).build();
}
When I run the above code, it returns json string like this :
{"records":[{"Name":"Sara"},{"Name":"David"}]}
The console log returns this :
Error : null Status : 0
What is the meaning of the null error? Or is there anything wrong with how I return the json string?
Try using JSON_STRINGIFY, this will convert your incoming data into String format.
console.log(JSON_STRINGIFY(response.data));
TO verify what data your web service is returning, you can always check it by hitting your web service via postman.
I managed to solve this by adding CORS (Access-Control-Allow-Origin) to the response header, based on another SO answer. There's no problem with my angular code, it's just that I need to modify my web service code to enable the CORS. So I just modified the part where it returns data to become like this :
return Response.status(200).entity(outerObject.toString()).header("Access-Control-Allow-Origin", "*").build();

How to retrieve json object in ajax onreadystatechange function

I have servlet calling in ajax call. It send json object in response. Now I have receive this json in jsp and place data in table format. Can someone help me in this. Here is my code,
I am calling servlet as,
xmlHttpReqRM.open('POST', "RTMobitor?rtype=rmonitor", true);
my servlet, Here vehicleList is a list object
latlng.setLng(resultSet.getString("lng"));
latlng.setStatus(resultSet.getString("status"));
latlng.setRdate(resultSet.getString("rdate"));
latlng.setRtime(resultSet.getString("rtime"));
vehicleList.add(latlng);
System.out.println(vehicleList);
String json = new Gson().toJson(vehicleList);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Previously I was sending response as a text, it was easy but now I changed to json. I am not getting how to receive,
xmlHttpReqRM.onreadystatechange = function() {
if (xmlHttpReqRM.readyState == 4) {
if (xmlHttpReqRM.status == 200) {
var responceeString = xmlHttpReqRM.responseText; // How to replace this ajax code for json
document.getElementById("flexme1").innerHTML = (responceeString);
} else {
alert('ERR OR: AJAX request status = ' + xmlHttpReqRM.status);
}
How can I replace this ajax code for json. Can anyone help me in this please.
var jsonObject = JSON.parse(responceeString);

How to get SoapUI request and response XML in java

I'm using the SoapUI API as part of an existing java project.
The application should save the request and response XML in an specific report file.
I wonder if it's possible to get those requests and responses via the API.
The method invoking the TestCaseRunner looks like this
protected void checkTestCase(TestCase testCase) {
TestCaseRunner tr = testCase.run(null, false);
for (TestStepResult tcr : tr.getResults()) {
String status = tcr.getStatus();
String time = tcr.getTimeTaken() + "ms";
/* How to get XML messages?
* String request =
* String response =
*/
}
}
Depending on exactly what kind of test steps you have they might be an instance of a MessageExchange. Casting the TestStepResult to a MessageExchange and calling getRequestContent / getResponseContent might do the trick.
String request = ((MessageExchange)tcr).getRequestContent();
String response = ((MessageExchange)tcr).getResponseContent();
I have used the following way to get the response from the API CAll performed:
runner = testRunner.runTestStepByName("Your Test Case name");
// Here we take the response in ms of the API call
timeTaken = runner.response.timeTaken;
// here we get the HTTP response code.
responseCode = runner.getResponseHeaders()."#status#";
// here we get the response content
String response = runner.getResponseContent();
// here we get the API call endpoint -> in case you need to print it out.
String endPoint = runner.getEndpoint();

Categories