How to pass parameters in a request? - java

I try to put data from the NewOrderRequest(pojo) class into the parameters :
#Query("params") NewOrderRequest params
but I get this result:
resultQueryString: params com.example.city.Model.NewOrderRequest#f45c8ad
expectation result:
resultQueryString: params +911
Data setting:
NewOrderRequest newOrderRequest = new NewOrderRequest();
newOrderRequest.setPhone("+911");
NetworkService.getInstance()
.service()
.newOrder(newOrderRequest)
Request:
#Headers({"Accept:application/json", "Content-Type:application/json;"})
#POST("RemoteCall?method=Taxi.WebAPI.NewOrder")
Call<RegResponse>newOrder(#Header("Cookie") String setCookie,#Query("params") NewOrderRequest params);
Please tell me how to pass the phone to the parameter?

You are sending an Object in #Query param, Only #Body accepts the object as its param. What you want is to convert your Object into JsonObject. I assume you're using Gson Library.
NewOrderRequest newOrderRequest = new NewOrderRequest();
newOrderRequest.setPhone("+911");
NetworkService.getInstance()
.service()
.newOrder(new Gson().toJson(newOrderRequest))

Try below code
#Headers({"Accept:application/json", "Content-Type:application/json;"})
#POST("RemoteCall?method=Taxi.WebAPI.NewOrder")
Call<RegResponse>newOrder(#Header("Cookie") String setCookie,#Query("params") String phone);

As it is a post request, and the intention is to send the data as an json object, the data is better sent in the request body rather than query param. Also any sensitive details should be part of request body.

Related

Rest API consumption without using a response bean

I want to consume a rest service which returning bunch of values.
The bean look like follows.
Class Customer{
Name, Address, Age ---etc // Almost 200 fields are there. Including reference to many objects as well. So it is very hard to create a bean for accepting the response.
}
Is there any alternative way to consume the response.
Customer customer = restTemplate.getForObject(http://testurl);
This is not I need. I need any other way to consume the service without creating the bean.
Using Spring Boot,Java 8
You probably might want to try to get JSONObject on your client side if you don't want to create a heavyweight DTO. Something along the lines:
String str = restTemplate.getForObject("http://testurl", String.class);
JSONObject myCustomer = new JSONObject(str);
String name = myCustomer.getString("name");
JSONObject address = myCustomer.getJSONObject("address"); // if address is a composite object with city, street, etc...
You could get the response in a JSON format and use JSONObject class to extract the data.
Example:
String response = restTemplate.getJSONObject(http://testurl);
JSONObject params = new JSONObject(response);
if(params.has("Name"))
String customerName = params.getString("Name");

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

What is the best way to pass multiply parameters as one http query parameter?

I have java web application (servlet) that does user authentication using SalesForce Server OAuth Authentication Flow. This OAuth Authentication provides "state" query parameter to pass any data on callback. I have a bunch of parameters that I want to pass through this "state" query param. What is the best way to do it? In java in particularly?
Or in other words, what is the best way to pass an array or map as a single http query parameter?
You can put all in json or xml format or any other format and then encode in base64 as a one large string. Take care that params can impose some hard limit on some browser/web server.
So, I have done it this way. Thank you guys! Here are some code snippets to illustrate how it works for me:
// forming state query parameter
Map<String, String> stateMap = new HashMap<String, String>();
stateMap.put("1", "111");
stateMap.put("2", "222");
stateMap.put("3", "333");
JSONObject jsonObject = new JSONObject(stateMap);
String stateJSON = jsonObject.toString();
System.out.println("stateJSON: " + stateJSON);
String stateQueryParam = Base64.encodeBase64String(stateJSON.getBytes());
System.out.println("stateQueryParam: " + stateQueryParam);
// getting map from state query param
ObjectMapper objectMapper = new ObjectMapper();
stateMap = objectMapper.readValue(Base64.decodeBase64(stateQueryParam.getBytes()), LinkedHashMap.class);
System.out.println("stateMap: " + stateMap);
Here is output:
stateJSON: {"1":"111","2":"222","3":"333"}
stateQueryParam: eyIxIjoiMTExIiwiMiI6IjIyMiIsIjMiOiIzMzMifQ==
stateMap: {1=111, 2=222, 3=333}

Getting one field from response entity json

i need to connect to a rest service to get the user id by using a token.
List<Object> providers = new ArrayList<>();
providers.add(new JacksonJaxbJsonProvider());
client = WebClient.create(properties.getProperty(URL), providers);
client = client.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE);
client.path(PATH + token);
Response response = client.get();
The entity of response have this format:
{"message":"Token is valid","userId":1}
To get the userId, i have:
response.readEntity(AuthResponse.class).userId;
It is possible to take only the userId without creating an class with that format ? (without AuthResponse.class)
You can try to read your JSON as Map, for example: response.readEntity(Map.class).get("userId")
Please refer to this page for more information.

Please check the code and give me why there is this error?

this is my servlet code
List<Group> list= dao.findgroup(user);
JSONObject json=(JSONObject) JSONSerializer.toJSON(list);
ServletResponse response=ActionContext.getServletResponse();
response.setContentType("text/JSON");
PrintWriter out=response.getWriter();
out.println(json);
out.close();
//this is my jquery code
$.get("viewgroup.process",function(data){
var use=$.parseJSON(data);
$(use).each(function(i,v)
{
var det="<tr><td>"+v.value+"</td><td>"+v.description+"</td><td>"+v.code+"</td><td>"+v.status+"</td><td><a href='#'>reset code</a></td><td><a href='#'>change status</a></td></tr>";
$(det).appendTo("#tablebody");
});
Now my problem is when i am sending this request and getting a list as json object,and when I use method parseJSON it gives me error:
SyntaxError: JSON.parse: unexpected character
Can any one tell me why this error is there?
Pretty sure the data parameter when using $.get is already a javascript object (rather than a JSON string), so no need to parse it again:
$.get("viewgroup.process",function(data){
var use = data;//or just use data directly rather that a new variable called use
$(use).each(function(i,v)
{
var det="<tr><td>"+v.value+"</td><td>"+v.description+"</td><td>"+v.code+"</td><td>"+v.status+"</td><td><a href='#'>reset code</a></td><td><a href='#'>change status</a></td></tr>";
$(det).appendTo("#tablebody");
});
//rest of code...
});
Change out.println(json); to out.println(json.toString()); in your servlet code. You want to send out the stringified JSON, not the actual object.
http://www.json.org/javadoc/org/json/JSONObject.html#toString%28%29

Categories