How to Send post request using resttemplate in android in the following format?
{"UserInfo":{"Password":"TEST99","UserName":"TEST99"}}
hope to get a reply soon.
You should add something like this while sending request
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
and this well while making RequestBody
RequestBody body = RequestBody.create(JSON, json);
I think basically you want to convert encoding type to JSON.
Code you interface like this
#POST("yoururl")
Call<ResponseClass> someMethodName(#Body Example example );
Where You need to send Example class object and you can get Example clss by posting you jSON in http://www.jsonschema2pojo.org/
Related
Currently, I am using the below java code. Here, I am passing parameters in the url.
RequestBody jsonRequestBody = RequestBody.create(mediaType, jsonBody.toString());
Request request = new Request.Builder()
.url("http://x.x.x.x:8080/v1/m?identifier=" + identifier)
.addHeader("claim", claim)
.post(jsonRequestBody)
.build();
Response response = client.newCall(request).execute();`
The problem is that my spring boot api has '#RequestBody Class obj' and '#RequestParam identifier' as the parameters. As obj is the object of class 'Class', the passed request body will be automatically converted to the respective obj(implementing serializable). I don't want to pass query parameters in the request body; rather I want to pass it separately.
I am unable to pass post parameters as well as request body separately using OkHttp. I tried looking up various resources but no luck. Can anyone help me out with this?
Avoid using .put() method because it should be used when you want to replace something that you have already sent.
Instead use post method when you want to submit data for the first time:
.post(formBody)
where
RequestBody formBody = new FormBody.Builder()
.add("message", "Your message")
.build();
See here for details: https://stackoverflow.com/a/35135972/1244696
I am using Retrofit for server calls. I need to send a JSONArray to the server. My JSONArray looks like -
[{"callName”:”xxx”},{“inputData":{"deviceImei”:”xxxx”,”appVersionUser”:”x”,”osVersion”:”x”,”osType”:”x”,”deviceToken”:”xxxx”}}]
I am using RetroFit version 1.9.0 . I tried to use #BODY. But I am getting this error -
retrofit.RetrofitError: APIClass.GetClientAuthentication: #Body parameters cannot be used with form or multi-part encoding"
My Api function declaration is,
#FormUrlEncoded
#POST("/XYZ")
void GetClientAuthentication(#Body JSONArray jArray,
Callback<AuthenticationCallBack> aPOJOCallback);
Can anybody help?
Thanks in advance.
Hey i solved it finally
At the receiving part i took response in JSONElement and converted it to POJO class like below. AuthenticationErrorJsonResponse.java is my POJO class.
ArrayList<AuthenticationErrorJsonResponse> yourArray = new Gson().fromJson(authenticationJsonResponse.toString(),
new TypeToken<List<AuthenticationErrorJsonResponse>>(){}.getType());
I am using retrofit an get Bad Request , I would want to know if there is a place in this library where builds the full JSON in string format before sending it.
If it's about inspecting the JSON at runtime for debugging purposes, you can call setLogLevel(LogLevel.FULL) on your RestAdapter.Builder.
FULL logs the headers, body and metadata for both requests and responses to logcat.
new String(((TypedByteArray) request.getBody()).getBytes());
In order to build a JSON formatted body, create an object with a class whose properties are the same that you want to send to the server. The GSON Library set up (or whichever library you are using) with the RestAdapter should send the request with the body in JSON format.
Also ensure that the call is #POST annotated and the parameter annotd with #Body Below is an example:
#POST("/login")
User login(#Body LoginUser loginUser);
I'm trying to POST a JSONObject using the Retrofit library, but when I see the request at the receiving end, the content-length is 0.
In the RestService interface:
#Headers({
"Content-type: application/json"
})
#POST("/api/v1/user/controller")
void registerController(
#Body JSONObject registrationBundle,
#Header("x-company-device-token") String companyDeviceToken,
#Header("x-company-device-guid") String companyDeviceGuid,
Callback<JSONObject> cb);
And it gets called with,
mRestService.registerController(
registrationBundle,
mApplication.mSession.getCredentials().getDeviceToken(),
mApplication.mSession.getCredentials().getDeviceGuid(),
new Callback<JSONObject>() {
// ...
}
)
And I'm certain that the registrationBundle, which is a JSONObject isn't null or empty (the other fields are certainly fine). At the moment the request is made, it logs out as: {"zip":19312,"useAccountZip":false,"controllerName":"mine","registrationCode":"GLD94Q"}.
On the receiving end of the request, I see that the request has Content-type: application/json but has Content-length: 0.
Is there any reason why sending JSON in the body like this isn't working? Am I missing something simple in using Retrofit?
By default, you don't need to set any headers if you want a JSON request body. Whenever you test Retrofit code, I recommend setting .setLogLevel(RestAdapter.LogLevel.FULL) on your instance of RestAdapter. This will show you the full request headers and body as well as the full response headers and body.
What's occurring is that you are setting the Content-type twice. Then you're passing a JSONObject, which is being passed through the GsonConverter and mangled to look like {"nameValuePairs":YOURJSONSTRING} where YOURJSONSTRING contains your complete, intended JSON output. For obvious reasons, this won't work well with most REST APIs.
You should skip messing with the Content-type header which is already being set to JSON with UTF-8 by default. Also, don't pass a JSONObject to GSON. Pass a Java object for GSON to convert.
Try this if you're using callbacks:
#POST("/api/v1/user/controller")
void registerController(
#Body MyBundleObject registrationBundle,
#Header("x-company-device-token") String companyDeviceToken,
#Header("x-company-device-guid") String companyDeviceGuid,
Callback<ResponseObject> cb);
I haven't tested this exact syntax.
Synchronous example:
#POST("/api/v1/user/controller")
ResponseObject registerController(
#Body MyBundleObject registrationBundle,
#Header("x-company-device-token") String companyDeviceToken,
#Header("x-company-device-guid") String companyDeviceGuid);
I want to send POST request to server. I have to pass JSON object as a parameter, and get JSON as a response, but I am getting this error:
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [com.package.Response] and content type [application/octet-stream]
Code
Sending request:
#RestService
RestClient restClient;
...
String json = "{\"param\":3}";
restClient.getRestTemplate().getMessageConverters().add(new GsonHttpMessageConverter());
Response res = restClient.send(json);
RestClient
#Rest("http://my-url.com")
public interface RestClient
{
#Post("/something/")
Response send(String json);
RestTemplate getRestTemplate();
void setRestTemplate(RestTemplate restTemplate);
}
I'm using these JAR files:
spring-android-rest-template-1.0.0.RC1
spring-android-core-1.0.0.RC1
spring-android-auth-1.0.0.RC1
gson-2.2.2
What I'm doing wrong? When I change send parameter to JSONObject I am getting the same error.
Btw. AA docs are really enigmatic - can I use Gson anyway? Or should I use Jackson? Which file do I need to include then?
Thanks for any help!
You can use RestTemplate with either Gson or Jackson.
Gson is fine and easier to use of you have small json data set. Jackson is more suitable if you have a complex / deep json tree, because Gson creates a lot of temporary objects which leads to stop the world GCs.
The error here says that it cannot find a HttpMessageConverter able to parse application/octet-stream.
If you look at the sources for GsonHttpMessageConverter, you'll notice that it only supports the mimetype application/json.
This means you have two options :
Either return the application/json mimetype from your content, which would seam quite appropriate
Or just change the supported media types on GsonHttpMessageConverter :
String json = "{\"param\":3}";
GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
converter.setSupportedMediaTypes(new MediaType("application", "octet-stream", Charset.forName("UTF-8")));
restClient.getRestTemplate().getMessageConverters().add(converter);
Response res = restClient.send(json);
I just had this problem. After several hours I realised that the class I was passing in to the RestTemplate.postForObject call had Date variables. You need to make sure it only contains simple data types. Hope this helps someone else!
I have to modify it little to work:
final List<MediaType> list = new ArrayList<>();
list.addAll(converter.getSupportedMediaTypes());
list.add(MediaType.APPLICATION_OCTET_STREAM);
converter.setSupportedMediaTypes(list);