The body option is used to control the body of an entity enclosing request (e.g., PUT, POST, PATCH). in PHP it is used like this
$client->request('POST', '/post', ['body' => $stream]);
But I want to use in java like http://crawler.ankiti.com having json
{
"data": [
{
"url": "http:\/\/crawler.ankiti.com\/?module=server&do=test",
"method": "post",
"options": {
"body": "post body test 1"
},
"target": "wo"
},
{
"url": "http:\/\/crawler.ankiti.com\/?module=server&do=test",
"method": "post",
"target": "wo",
"options": {
"body": "post body test 1",
"form_params": {
"name": "abhay",
"surname": "aggarwal"
},
"headers": {
"login": "abhay",
"password": "patparganj405"
}
}
},
{
"url": "http:\/\/crawler.ankiti.com\/?module=server&do=test",
"method": "post",
"target": "wo",
"options": {
"multipart": [
{
"name": "file text",
"path": "\/test\/file.txt"
},
{
"name": "file image",
"path": "\/test\/file.jpg"
}
]
}
}
],
"errors": "",
"meta": ""
}
I want to post a string in a body request which is present in json of this url.
You can use httpServlet and follow a procedure like this.
response.setContentType("application/json");
// Get the printwriter object from response to write the required json object to the output stream
PrintWriter out = response.getWriter();
// Assuming your json object is **jsonObject**, perform the following, it will return your json object
out.print(jsonObject);
out.flush();
Hope this helps
Related
I'm having difficulty implementing a JSON to send as a POST call in Spring.
Which is the fastest and most effective way to turn this json into a java object or a map and make the call?
below is an example of a json to send:
{
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": {
"name": "edge-ws"
},
"spec": {
"selector": {
"matchLabels": {
"run": "edge-ws"
}
},
"replicas": 1,
"template": {
"metadata": {
"labels": {
"run": "edge-ws"
}
},
"spec": {
"containers": [
{
"name": "edge-ws",
"image": "server-tim:latest",
"imagePullPolicy": "Never",
"ports": [
{
"containerPort": 80
}
]
}
]
}
}
}
}
this and the second body that has a value (nodeport) that must be taken from a field entered by the user front end side.(page created in html)
{
"apiVersion": "v1",
"kind": "Service",
"metadata": {
"name": "edge-ws",
"labels": {
"run": "edge-ws"
}
},
"spec": {
"type": "NodePort",
"ports": [
{
"port": 8080,
"targetPort": 80,
"nodePort": 30200,
"protocol": "TCP",
"name": "http"
}
],
"selector": {
"run": "edge-ws"
}
}
}
Both files must be sent with a single click on a button on the front end side.the first call with the first body starts and if everything is ok the second body starts
What should the class that maps objects look like? What should the controller look like instead?
They also gave me an address to call that can only be used on the machine, how can I test this call locally?
Thanks in advance!
You can use google's Gson library to convert the JsonString to Object and then use below code:
Gson gson = new Gson();
Object requestObject = gson.fromJson(jsonString, Object.class);
ResponseObject responseObject = restTemplate.postForObject(url, requestObject, ResponseObject.class);
I am trying to create one mapping.json under the mappings folder with multiple stubs as below. But I am facing the following error
Wiremock: v2.5.1 (standalone)
Mapping.json file looks,
[
{
"scenarioName": "Savings account Stub",
"request": {
"url": "/ws/*****",
"method": "POST",
"bodyPatterns" : [{
"contains" : "AccountRequest"
}
]
},
"response": {
"status": 200,
"bodyFileName": "******"
}
},
{
"scenarioName": "Current account Stub",
"request": {
"method": "POST",
"url": "/ws/*****",
"bodyPatterns": [
{
"contains": "AccountListRequest"
}
]
},
"response": {
"status": 200,
"bodyFileName": "******"
}
}]
Error:
Exception in thread "main" wiremock.com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.github.tomakehurst.wiremock.stubbing.StubMapping out of START_ARRAY token
Is there any possibility to create multiple stubs for the same URL in single mapping file? Can anyone tell me what is the exact issue?
Looking at the stubbing documentation, I think you want your mappings.json to look like...
{
"mappings": [
{
"scenarioName": "foo",
"request": {},
"response": {}
}, {
"request": {}
}
],
"importOptions": {
"duplicatePolicy": "IGNORE",
"deleteAllNotInImport": true
}
}
You'd then want to make a POST request to /__admin/mappings/import with your mappings.json as the request body. The reason for this is that I believe multiple mappings in a single file are only supported via the import option.
In my play framework application, I have registered APIs in route file as:
POST /api/rmt-create-request controllers.Api.CreateRMTRequestForm
On action of controller, I am using following code to access formData submitted with form submit as :
public Result CreateRMTRequestForm()
{
Map<String, String[]> params = request().body().asMultipartFormData().asFormUrlEncoded();
Its working fine as API when I submit the form with forntend application.
I am trying to create APIs documentation with swagger.ui in which within swagger.json file I have written following JSON data.
"paths": {"/api/rmt-create-request": {
"post": {
"tags": [
"RMT APIs"
],
"description" : "Return newly created request data",
"operationId": "create-new-rmt-request",
"consumes": ["application/x-www-form-urlencoded"],
"parameters": [
{
"name": "rootNodeName",
"in": "formData",
"description": "Root node class name for item",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/rmt-request-data"
}
}
}
},
"default": {
"$ref": "#/components/responses/default"
}
}
}
},
While inspecting RequestHeader data, its not showing content-Type property with value 'multipart/form-data' as well as formData are not attached, which makes controller to throw null exception.
Can anyone help whats missing in swagger.json file ?
You are mixing OpenAPI 2.0 and 3.0 syntax.
In OpenAPI 3.0, request body (including form data) is defined using the requestBody keyword instead of in: formData parameters.
Also, OAS3 does not use consumes. The media types consumed by the operation are specified inside the requestBody.
"paths": {
"/api/rmt-create-request": {
"post": {
"tags": [
"RMT APIs"
],
"description": "Return newly created request data",
"operationId": "create-new-rmt-request",
"requestBody": {
"content": {
"multipart/form-data": { // or "application/x-www-form-urlencoded" - depending on what you need
"schema": {
"type": "object",
"properties": {
"rootNodeName": {
"type": "string",
"description": "Root node class name for item"
}
}
}
}
}
}
}
}
}
More information: Describing Request Body
Doing some request to the backend API, for receiving some array with JSON objects which I need to use in test run.
Using RestAssured+Junit5+Gradle+Allure.
Response response =
given()
.header("Content-Type", "application/json")
.body(jsonPayload)
.when()
.post(STAGINGSCHEDULE+signature)
.then()
.assertThat()
.statusCode(200)
.body("message", is("Payload valid"),
"payment_schedule", hasSize(greaterThan(0)))
.extract().response();
I would receive this:
ArrayList<JsonElement> jsonElement = response.path("payment_schedule.payment_dates");
This command will show me an array filled with json objects which I needed.
But a cound not convert this to the gson.JsonObject.
System.out.println("jsonElement.get(1): "+jsonElement.get(1));
Which methods I used to usually, when generating data by myself. Object is gsonObject, and array is gsonArray
callbackJournalObject.add("schedule", scheduleArray);
When I try to use
callbackJournalObject.add("schedule", jsonElement.get(1));
I get
java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.google.gson.JsonElement
JSON Response body example:
{
"status": 0,
"message": "Payload valid",
"payment_schedule": [
{
"total": 16800.0,
"term": 3,
"payment_dates": [
{
"date": "16.10.2018",
"amount": 5600.0
},
{
"date": "16.11.2018",
"amount": 5600.0
},
{
"date": "17.12.2018",
"amount": 5600.0
}
]
},
{
"total": 16650.0,
"term": 6,
"payment_dates": [
{
"date": "16.10.2018",
"amount": 2800.0
},
{
"date": "16.11.2018",
"amount": 2800.0
},
{
"date": "17.12.2018",
"amount": 2800.0
},
{
"date": "16.01.2019",
"amount": 2800.0
},
{
"date": "18.02.2019",
"amount": 2800.0
},
{
"date": "18.03.2019",
"amount": 2650.0
}
]
}
]
}
That solution worked for me.
ArrayList<JsonElement> jsonElement = response.path("payment_schedule.payment_dates");
String jsonElementGet1 = String.valueOf(jsonElement.get(1));
scheduleArray = (JsonArray)jsonParser.parse(jsonElementGet1);
You need to remove the last comma at the end of the JSON as with it, it's not valid JSON. Once you've done that, try again and see if it works. (Used JSONBlob to verify the validity of the JSON).
I need to send a HTTP Post to a REST API with the following complex type as parameters. I looked at the documentation of jersey and it helps only to send a key value pair. How can i send a HTTP Post request with the below parameters using jersey.
{
"key": "example key",
"message": {
"html": "<p>Example HTML content</p>",
"text": "Example text content",
"subject": "example subject",
"from_email": "message.from_email#example.com",
"from_name": "Example Name",
"to": [
{
"email": "recipient.email#example.com",
"name": "Recipient Name"
}
],
"headers": {
"Reply-To": "message.reply#example.com"
},
"important": false,
"track_opens": null,
"track_clicks": null,
"auto_text": null,
"auto_html": null,
"inline_css": null,
"url_strip_qs": null,
"preserve_recipients": null,
"view_content_link": null,
"bcc_address": "message.bcc_address#example.com",
"tracking_domain": null,
"signing_domain": null,
"return_path_domain": null,
"merge": true,
"global_merge_vars": [
{
"name": "merge1",
"content": "merge1 content"
}
],
"merge_vars": [
{
"rcpt": "recipient.email#example.com",
"vars": [
{
"name": "merge2",
"content": "merge2 content"
}
]
}
],
"tags": [
"password-resets"
],
"subaccount": "customer-123",
"google_analytics_domains": [
"example.com"
],
"google_analytics_campaign": "message.from_email#example.com",
"metadata": {
"website": "www.example.com"
},
"recipient_metadata": [
{
"rcpt": "recipient.email#example.com",
"values": {
"user_id": 123456
}
}
],
"attachments": [
{
"type": "text/plain",
"name": "myfile.txt",
"content": "ZXhhbXBsZSBmaWxl"
}
],
"images": [
{
"type": "image/png",
"name": "IMAGECID",
"content": "ZXhhbXBsZSBmaWxl"
}
]
},
"async": false,
"ip_pool": "Main Pool",
"send_at": "example send_at"
}
I looked at the other questions of sending HTTP Post using Jersey and all I could find was a way to only send a key\value pairs as parameters and not complex string types like above.
You should look at JAXB, it allows you to "automatically" build "complex parameters" out of "objects". Basically the procedure would be to define a class that represents the data structure you present as request message the REST API resource accepts, then populate it with the data your want to POST and send it. In this question you can find more details on how to exactly do that: Can jersey clients POST a JAXB object to the server using JSON?