how to parse this web service using retrofit in android? - android

http://www.superbinstruments.com/directory/index.php?r=webservice/profile/id/4096
Here i want to pass ID in the URL (like above) and JsonObject (can be null) in the Body.
Here the concept is like when i pass null to the json object it will retrieve the profile data or if i pass the json object with profile information then it will update the profile data.
I have tried below methods but i can retrieve the data but i can not update the data.
To update the data we we can pass same JSON response as Body.
#POST("index.php")
Call<UserProfile> profileUser(#Query("r") String value, #Body String user);
#POST("index.php?")
Call<UserProfile> saveUser(#Query("r") String value, #Body JSONObject user);
I am passing like:
value= webservice/profile/id/4096
if I pass as Json String as profile updated info then i am getting
"Invalid request password not needed."
OR
if I will pass as JsonObject as profile updated info
then i am getting
java.lang.OutOfMemoryError: OutOfMemoryError thrown while trying to throw OutOfMemoryError; no stack trace available

The link you have posted not required any body to post. Remove Body from your code. To use #Field you have to annotate method as #FormUrlEncoded
Your method should be like this.
#FormUrlEncoded
#POST("index.php?r=webservice/profile/id/")
Call<UserProfile> saveUser(#Field("value") String value);
Hope it helps:)

Please try this way
#POST("index.php")
Call<User> getInstruments(#Query("r") String webservice, #Body User user);
And you should have to pass JSON using your model class as Bhuvanesh suggested
JSONObject jObj = null;
try {
jObj = new JSONObject();
jObj.put("firstname", "Kunjan Shah");
} catch (JSONException ex) {
ex.printStackTrace();
}
User user = new User();
user.setData(jObj);
And here is your model class
public class User {
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public JSONObject getData() {
return data;
}
public void setData(JSONObject data) {
this.data = data;
}
String success;
String message;
JSONObject data;
}
And call your service by passing this two parameter
Call update_user_profile =
yourapiinterfaceobject.getInstruments("webservice/profile/id/4096", user);

Related

How do I call retrofit along with greendao for post request?

I am trying to integrate greendao with the retrofit. This link will give an idea ( https://i.stack.imgur.com/7qmbu.jpg) of how the data is sent to the server. It is a post request and I am really confused about how to call this request via retrofit.
It will be really helpful if someone can help me with it.
In API response I am getting an request object, response object, message and status code.
response object I have fields about the user and in request object I have field about the information that is being send.
another picture here
https://i.stack.imgur.com/a5DBz.jpg
You can create response like this using this method
private String create(String email, String password) {
try {
JSONObject cell1 = new JSONObject();
JSONObject jsonObject = new JSONObject();
cell1.put("email", email);
cell1.put("password", password);
jsonObject.put("data", cell1);
return jsonObject.toString();
} catch (Exception e) {
return e.getMessage();
}
}
Call you POST as this
#FormUrlEncoded
#POST("your_path_here")
Call<String> uploadData(#Body String obj);
in your Activity
String json = create("your_email", "your_password");
apiInterface.uploadData(json).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});

How to convert retrofit response into json object

I just wanted to know that how could I convert this retrofit library response which is actually a JSON response to JSON object so I could use this in my android app to do something because I can not do anything with response in the buffered reader.
public void getMe(){
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(ROOT_URL)
.build();
myApi api = adapter.create(myApi.class);
api.sendme(
userEmail,
rs,
Team1,
Team2,
new retrofit.Callback<retrofit.client.Response>() {
#Override
public void success(retrofit.client.Response result, retrofit.client.Response response) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
if (!output.equals("")) {
output = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void failure(RetrofitError error) {
// loading.dismiss();
Toast.makeText(Leaderboard.this, "", Toast.LENGTH_LONG).show();
}
}
);
}
here get me is sending post response to the server
public interface myApi {
#FormUrlEncoded
#POST("/myleaderboard.php")
void sendme(
#Field("userEmail") String userEmail,
#Field("rs") String rs,
#Field("team1") String team1,
#Field("team2") String team2,
Callback<Response> callback);
}
I m getting JSON response and I have to store that in my android code somehow whether that be using JSON object or anything else if possible.
please help me with this
Just change the myAPi code to
public interface myApi {
#FormUrlEncoded
#POST("/myleaderboard.php")
void sendme(
#Field("userEmail") String userEmail,
#Field("rs") String rs,
#Field("team1") String team1,
#Field("team2") String team2,
Callback<JsonObject> callback);
}
it will return JsonObject directly
Use GsonConverterFactory to convert incoming json into model/pojo class
implementation 'com.squareup.retrofit2:converter-gson:LATEST_VERSION'
Please go through following links
Retrofit Library Tutorial
Consuming-APIs-with-Retrofit
Use this link to convert your JSON into POJO with select options as selected in image below [http://www.jsonschema2pojo.org/
You will get a POJO class for your response like this
public class Result {
#SerializedName("id")
#Expose
private Integer id;
/**
*
* #return
* The id
*/
public Integer getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}
then and use interface like this:
#FormUrlEncoded
#POST("/api/level")
Call<Result> checkLevel(#Field("id") int id);
add the dependencies
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.+'
and call like this:
Call<Result> call = api.checkLevel(1);
call.enqueue(new Callback<Result>() {
#Override
public void onResponse(Call<Result> call, Response<Result> response) {
response.body(); // have your all data
int id =response.body().getId();
String userName = response.body().getUsername();
String level = response.body().getLevel();
}
#Override
public void onFailure(Call<Result> call, Throwable t) {
}
});
to get the response in JSON don't use addConverterFactory(GsonConverterFactory.create()) from Retrofit.

How to get nested string from JsonElement?

I am getting JSonElement as Response from retrofit and I want to get only a string from it's object, so how can I achieve it ? I have browsed over too many sites but nothing found
RestClient.get().getVoterSlip("Bearer " + Constants.ACCESS_TOKEN, new Callback<JsonElement>() {
#Override
public void success(JsonElement jsonElement , Response response) {
// want to get a string here from jsonElement
}
#Override
public void failure(RetrofitError error) {
}
});
I do not want to cast it with model class.
If you could share ur Json response, we could help you better.
But first get the JsonObject and then get the string that you want.
for example,
JSONObject jsonObj = array.getJSONObject(0); String theString =
jsonObj.getString("NeededString");
Refer https://developer.android.com/reference/org/json/JSONObject.html

Not able to complete the Retrofit request?

I have to send the JSON as a Post request through Retrofit. To this I have created a Json Object :
private JSONObject yourJSON(){
JSONObject jsonRoot = new JSONObject();
JSONObject jsonObject1 = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject2 = new JSONObject();
try{
jsonArray.put(jsonObject2);
jsonObject2.put("duration", "12");
jsonObject1.put("region", "NYC");
jsonObject1.put("or", jsonArray);
jsonRoot.put("q", jsonObject1);
jsonRoot.put("sort", "recent");
}catch (JSONException e){
e.printStackTrace();
}
return jsonRoot;
}
Then I am using this JSON to send the data by following code
RestApiAdapter restAdapter = new RestApiAdapter();
RoomListingAPI apiservice = restAdapter.providesRestAdapter().create(RoomListingAPI.class);
JSONObject response = apiservice.getRoomListing("qwerty","application/json", yourJSON());
API method
public interface RoomListingAPI {
#POST("/api/listings/search")
JSONObject getRoomListing(#Header("x-parse-session-token") String token, #Header("Content-Type") String type, #Body JSONObject json);
}
My goal is to send the JSON and received the JSON but it's not working. What I am doing wrong here. I am also sending the correct JSON. What I am doing wrong here?
You should call your network operation on a background task instead. Otherwise, NetworkOnMainThreadException will be thrown.
Now retrofit has two modes. Synchronous or Asynchronous.
You're using a synchronous mode, presumably called in your main thread.
What you can do now is to change to asynchronous mode (using retrofit callback).
That is, change from:
public interface RoomListingAPI {
#POST("/api/listings/search")
JSONObject getRoomListing(#Header("x-parse-session-token") String token, #Header("Content-Type") String type, #Body JSONObject json);
}
To:
public interface RoomListingAPI {
#POST("/api/listings/search")
void getRoomListing(#Header("x-parse-session-token") String token, #Header("Content-Type") String type, #Body JSONObject json, Callback<JsonObject> responseCallback);
}
To get the JsonObject return response:
apiservice.getRoomListing("qwerty","application/json", yourJSON(),
new Callback<JsonObject>() {
#Override
public void success(JsonObject jsonObject, Response response) {
// jsonObject is what you're looking for
}
#Override
public void failure(RetrofitError error) {
// do something with the error
}
});
Also, it's better to use gson library. Thus use JsonObject instead of JSONObject. Different letter-case, different library, better performance.

Getting simple JSON object response using Retrofit library

I have a web query with JSON response as:
{
"status":true,
"result":
{
"id":"1",
"name":"ABC 1",
"email":"info#ABc.dcom",
"password":"123456",
"status":false,
"created":"0000-00-00 00:00:00"
},
"message":"Login successfully"
}
I am using the following code for:
#GET("/stockers/login")
public void login(
#Query("email") String email,
#Query("password") String password,
Callback<JSONObject> callback);
In Debugger the query made by the Retrofit library is correct, however I get an empty JSON in response.
ApiManager.getInstance().mUrlManager.login(
email.getText().toString().trim(),
password.getText().toString().trim(),
new Callback<JSONObject>()
{
#Override
public void success(JSONObject jsonObj, Response response)
{
mDialog.dismiss();
Simply use JsonElement insted of JSONobject. Like:
#GET("/stockers/login")
Call<JsonElement> getLogin(
#Query("email") String email,
#Query("password") String password
);
The answers seam kinda old and for Retrofit 1, if you are using Retrofit 2 and don't want to use a converter you have to use ResponseBody.
#GET("/stockers/login")
public void login(
#Query("email") String email,
#Query("password") String password,
Callback<ResponseBody> callback);
And then in your callback in the onResponse method call string on the body and create a JSONObject from it.
if(response.isSuccessful())
JSONObject json = new JSONObject(response.body().string());
Instead of Callback with JSONObject class, you could use the Retrofit basic callback which use the Response class and then, once you get the response, you had to create the JSONObject from it.
See this:
https://stackoverflow.com/a/30870326/2037304
Otherwise you can create your own model class to handle the response.
First the Result class:
public class Result {
public int id;
public String name;
public String email;
public String password;
public boolean status;
public Date created;
}
And then your response class to use with Retrofit
public class MyResponse {
public boolean status;
public Result result;
public String message;
}
Now you can call:
#GET("/stockers/login")
public void login(
#Query("email") String email,
#Query("password") String password,
Callback<MyResponse> callback);
You can create custom factory like belowe or copy it from here :
https://github.com/marcinOz/Retrofit2JSONConverterFactory
public class JSONConverterFactory extends Converter.Factory {
public static JSONConverterFactory create() {
return new JSONConverterFactory();
}
private JSONConverterFactory() {
}
#Override public Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
if (type == JSONObject.class
|| type == JSONArray.class) {
return JSONRequestBodyConverter.INSTANCE;
}
return null;
}
#Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
if (type == JSONObject.class) {
return JSONResponseBodyConverters.JSONObjectResponseBodyConverter.INSTANCE;
}
if (type == JSONArray.class) {
return JSONResponseBodyConverters.JSONArrayResponseBodyConverter.INSTANCE;
}
return null;
}
}
public class JSONRequestBodyConverter<T> implements Converter<T, RequestBody> {
static final JSONRequestBodyConverter<Object> INSTANCE = new JSONRequestBodyConverter<>();
private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain; charset=UTF-8");
private JSONRequestBodyConverter() {
}
#Override public RequestBody convert(T value) throws IOException {
return RequestBody.create(MEDIA_TYPE, String.valueOf(value));
}
}
public class JSONResponseBodyConverters {
private JSONResponseBodyConverters() {}
static final class JSONObjectResponseBodyConverter implements Converter<ResponseBody, JSONObject> {
static final JSONObjectResponseBodyConverter INSTANCE = new JSONObjectResponseBodyConverter();
#Override public JSONObject convert(ResponseBody value) throws IOException {
try {
return new JSONObject(value.string());
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
static final class JSONArrayResponseBodyConverter implements Converter<ResponseBody, JSONArray> {
static final JSONArrayResponseBodyConverter INSTANCE = new JSONArrayResponseBodyConverter();
#Override public JSONArray convert(ResponseBody value) throws IOException {
try {
return new JSONArray(value.string());
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
try this instead :
#GET("/stockers/login")
public void login(
#Query("email") String email,
#Query("password") String password,
Callback<Response> callback); // set the callback generic parameter to Response
ApiManager.getInstance().mUrlManager.login(
email.getText().toString().trim(),
password.getText().toString().trim(),
new Callback<Response>()
{
#Override
public void success(Response response, Response response1)
{
String json = response.getBody();
try {
JSONObject jsonObj = new JSONObject(json);
} catch(JSONException e) {
}
alog.dismiss();
Just define the type of the object you want to get as a String as com.google.gson.JsonObject instead of String and call .toString() on that object to get the JSON string itself.
I`m using this site to create my classes (POJO) from JSON.
http://www.jsonschema2pojo.org/
just be sure to set to JSON insted of JSON Schema and check GSON, because retrofit is using GSON as well for parsing.
your retrofit code looks fine.
Use JacksonConverterFactory instead of GsonConverterFactory while setting up Retrofit. Now you can directly work with JsonObject responses.
compile 'com.squareup.retrofit2:converter-jackson:2.1.0'

Categories

Resources