I encode data on response .
put the key on header.
Now I can decode on Observer when I get string data.
But I would like to do on GsonConverterFactory
then I can just decode on gsonConverterFactory and use gson data when response
I would like to know how to get header in GsonConverterFactory responseBodyConverter?
you need to add okhttpclient to your retrofit client for getting header
please refer this link
Related
I call a Rest API of salesforce by post method:
url = "https://test-dev-ed.my.salesforce.com/services/apexrest/AccountUsers/"
client = OkHttpClient()
val jsonIn = FormBody.Builder()
.add("email",URLEncoder.encode("dt1#gmail.com", "UTF-8"))
.add("password", URLEncoder.encode("1","UTF-8"))
.build()
request = Request.Builder()
.post(jsonIn)
.header("Authorization", "Bearer "+accesstoken)
.addHeader("Content-Type","application/x-www-form-urlencoded")
.url(url)
.build()
response = client.newCall(request).execute()
This is rest api:
#HttpPost
global static ID createUser(String email, String password) {
AccountUser__c us=new AccountUser__c();
us.Email__c=email;
us.Password__c=password;
us.Status__c=0;
insert us;
return us.Id;
}
But result return is error:
[{"errorCode":"UNSUPPORTED_MEDIA_TYPE","message":"Content-Type header specified in HTTP request is not supported: application/x-www-form-urlencoded"}]
I had try change application/json to application/x-www-form-urlencoded , but still can't resolve.
I try call a Get method, it is ok.
Why Post method occur error [Content-Type header specified in HTTP request is not supported]?
I would like to suggest a better resolution. Retrofit Library
Even though it is not mandatory to use Retrofit, these are few eye catchy aspects which makes it reliable and handy in similar use case of yours.
Why to use Retrofit?
Type-safe REST Adapter that makes common networking tasks easy
For POST operations, retrofit helps in assembling what needed to be submitted. Eg:- Generating URL encoded form.
Takes care of URL manipulation, requesting, loading, caching, threading, synchronization, sync/async calls
Helps to generate URL using type-aware generated code tied to specific REST API
Parsing JSON using GSON
Retrofit is an API adapter wrapped over OkHttp
The problem that you are facing can be resolved using retrofit like this.
public interface APIConfiguration{
#Headers({"Accept:application/json",
"Content-Type:application/x-www-form-urlencoded"})
#FormUrlEncoded
#POST("user/registration")
Observable<DataPojo> registrationAPI(#FieldMap(encoded = true) Map<String, String> params);
}
That's it, with few annotation the library takes care of Form URL
Encoding and related dependencies.
As it is inappropriate to start from corresponding Retrofit dependencies and sample code, you can go through Reference One and Reference Two for more details.
As per my understanding just checkout the difference the content type header "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.
The content "multipart/form-data" follows the rules of all multipart MIME data streams.
https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4
Also try your http request by setting your content type header as multipart/formdata.
How do I send the following object to server using retrofit 2:
{"list":[
{
"addrress1":
{"addressLine1":"EktaColony",
"addressLine2":"Warje",
"country":"India",
"state":"Maharashtra",
"city":"Pune",
"zipcode":411058},
},
{address2:{.....,.....,...}}
]}
I am using Rxjava.
You can send the json as body of HTTP request. Retrofit provides the annotation #Body for its use
So in your interface
#POST("/yourserver/api")
Observable<ResponseType> sendReq(#Body RequestParser parser);
Your RequestParser Object is the object mapped from the json string. You can use any Json serializer libraries like gson or jackson for it.
From server send Json, but Retrofit2 response is xml.
I've found a solution in this link.
retrofit solution
But this solution is retroft not retrofit2.
Use POJO Generator Plugin for custom converter response from JSON or XML, with it you can post JSON with XML response
and usage :
.setConverter(new MixedConverter(new SimpleXMLConverter(), new GsonConverter(gson)));
and use as in this
Use a custom converter with both JSON and XML converters as in this answer of the question that you referenced in the question. Then use that converter to create Retrofit instance.
Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(new MixedConverter(new SimpleXMLConverter(), GsonConverterFactory.create()))
.build();
ApiService apiService = retrofit.create(ApiService.class);
I am trying to make a simple weather app using retrofit library. I want the city name to be dynamic. This is what i have done so far:
full url:
http://api.openweathermap.org/data/2.5/forecast/daily?q=dhaka&cnt=7&appid=1111
base url:
http://api.openweathermap.org/
in the main activity
LinkedHashMap<String,String>data=new LinkedHashMap<>();
data.put("q",targetCity);
data.put("cnt",Integer.toString(7));
data.put("appid",getString(R.string.api_key));
Call<WeatherResponse>weatherResponseCall=weatherServiceApi.getAllWeatherReport(data);
and in my api interface:
#GET("data/2.5/forecast/daily?")
Call<WeatherResponse>getAllWeatherReport(#QueryMap LinkedHashMap<String,String>data);
I am neither getting any error, nor any response data.
Please help.
You aren't executing the call function...
WeatherResponse response = call.execute().body();
If I were you, I would try using a ResponseBody from okhttp to get the data returned. Then using response.string() you can see what's retrieved from the request.
Or, to log the body data of each request/response you should add this interceptor when building your Retrofit object:
OkHttpClient client = httpClient.addInterceptor(interceptor.setLevel(HttpLoggingInterceptor.Level.BODY))
.build();
Retrofit retrofit = builder.client(client).build();
return retrofit.create(serviceClass);
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);