Is it possible to POST a package of json objects? - android

so I am building an applications that has to POST a json array with some information and also json object with user credentials which are going to be used for identification. Is is possible to POST some kind of package that contains json object array + object with user credentials? I am using Retrofit2.
So beside this Array list I would like to send Credentials with one POST request.
public interface JsonPlaceHolderApi {
#POST("hws/hibisWsTemplate/api/v1/order/posts/")
Call<Post> createPost(#Body ArrayList<Post> post);
}

You have to do something like that
Define your API
public interface JsonPlaceHolderApi {
#POST("hws/hibisWsTemplate/api/v1/order/posts/")
Call<Post> createPost(#Body PostRequest post);
}
Define your request
public class PostRequest {
final ArrayList<Post> posts;
final String credentials; // or anything you want
PostRequest(ArrayList<Post> posts, String credentials) {
this.posts = posts;
this.credentials = credentials;
}
}

You have to create a class for credentials just like you made a class for your array. Then you create another class named lets say "Request" and put credentials and your array in it like so:
public class Request {
final ArrayList<Post> posts;
final Credentials credentials;
//constructor, getters/setters
...
and then in your api do this:
public interface JsonPlaceHolderApi {
#POST("hws/hibisWsTemplate/api/v1/order/posts/")
Call<Post> createPost(#Body Request post);
}

Related

What is API interface in Retrofit

While studying Retrofit Library I cae across API Interface I could not understand the Code/terms used inside it. Can anyone explain the lines of code??
public interface ApiInterface {
// For POST request
#FormUrlEncoded // annotation that used with POST type request
#POST("/demo/login.php") // specify the sub url for our base url
public void login(
#Field("user_email") String user_email,
#Field("user_pass") String user_pass, Callback<SignUpResponse> callback);
//user_email and user_pass are the post parameters and SignUpResponse is a POJO class which recieves the response of this API
// for GET request
#GET("/demo/countrylist.php") // specify the sub url for our base url
public void getVideoList(Callback<List<CountryResponse>> callback);
// CountryResponse is a POJO class which receives the response of this API
}
Thanks For any Response!!

Call webservice using Retrofit return invalid webservice result

I am using retrofit to retrieve login JSON result from server for that i need to post user name and password. I have tried this code but i get response saying invalid Web Service. but i get correct response using Rest.
My code is something like this,
MainActivity.java
String url = "http://***.***.in/***/******/*********/UserService.php?request=Verify_User_Credential";
//making object of RestAdapter
RestAdapter adapter = new RestAdapter.Builder().setEndpoint(url).build();
//Creating Rest Services
RestInterface restInterface = adapter.create(RestInterface.class);
//Calling method to get login report
restInterface.getLoginReport(username, password, new Callback<Model>()
{
#Override
public void success(final Model model, Response response) {
if (RetailConnectUtils.isSuccess(model.getStatus())) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// retrieve status and message from model and display
}
});
}
});
RestInterface::
#FormUrlEncoded
#POST("/GetData")
void getLoginReport(#Field("username")String uname,#Field("password")String password,Callback<Model> cb);
and POJO class model containing json converted values It contain method getStatus and getMessage...
Here what should i mention in #POST("******").. is that webservice method or default retrofit method?

Retrofit making empty body for request in Android

I am using Retrofit in android and GsonConverterFactory is converter.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://xxxxxxx.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
I want send POST request with body.
public class MasterRequest
{
}
public class User extends MasterRequest
{
#SerializedName("email")
public String email = null;
}
#POST("{path}")
Call<MasterResponse> registerUser(#Path("path") String path, #Body MasterRequest masterRequest);
path is the URL that append with base URL.
When ever I send child class("User") object in parent class reference(MasterRequest), then converter shown empty json; "{}".
But when I send User class object to below registerUser Method, then it working fine.
#POST("{path}")
Call<MasterResponse> registerUser(#Path("path") String path, #Body User user);
How can I send child class object in parent class instance to make request body?
That's how Gson works. The easiest way to serialize polymorphic objects is use RuntimeTypeAdapterFactory. You can find detailed tutorial here. Works great with Retrofit!

Is there a greate sample using the retrofit

I'm going to develop a small-sized system to raise my developing skills.
It consists of the three parts listed below:
1. Web DB
2. Web Page
3. Android App
The main feature is managing the members. (login, just showing the user information)
At this point, I'm wondering about the android app part.
Especially, the HTTP.
I found two libraries which are JSoup and Retrofit.
As far as I can tell, those libraries are a little bit different.
I think the retrofit is a better fit for me...
Up until now I couldn't find a good sample...
Can you give me a hint how to do this?
If you are trying to connect to a Web Database I would suggest using Volley which is really simple and straightforward and really powerful yet: https://developer.android.com/training/volley/index.html.
Here's an example on how you could set your query with volley from the android developer site:
final TextView mTextView = (TextView) findViewById(R.id.text);
...
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
Retrofit example
Synchronous
Interface
public interface RestApi {
#POST("/Login")
String login(#Body User user);
}
Simple class which follows the singleton design pattern
public class RestClient {
private static RestApi API_INSTANCE;
private static final String ENDPOINT = "http://192.168.6.99:50500/Phone";
static {
setUpHttpClient();
}
private static void setUpHttpClient() {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(ENDPOINT)
.setLogLevel(BuildConfig.DEBUG ?
RestAdapter.LogLevel.FULL :
RestAdapter.LogLevel.NONE)
.build();
API_INSTANCE = restAdapter.create(RestApi.class);
}
private RestClient() {}
public static RestApi getApiInstance() {
return API_INSTANCE;
}
}
Call it for example in an IntentService
String userToken = "";
try {
// post to http://192.168.6.99:50500/Phone/Login
userToken = RestClient.getApiInstance().login(new User(login, password));
} catch (RetrofitError error) {
//...
}
build.gradle
compile 'com.squareup.retrofit:retrofit:1.9.0'
Or Asynchronous
interface
public interface RestApi {
#POST("/Login")
void login(#Body User user, Callback<String> token);
}
and do the request with a callback..

Retrofit to consume APIs

I just started using Retrofit to consume APIs. I am able to update a User's profile successfully but I can't pass in the information to a User Object:
Interface RetrofitService:
public interface RetrofitService {
#FormUrlEncoded
#POST("/profile/update")
public void updateUser(
#Field("user_id") String userId,
#Field("user_token") String userToken,
#Field("first_name") String firstName,
#Field("last_name") String lastName,
Callback<JSONObject> callback);
}
Activity ProfileUpdate:
updateProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Build RestAdapter
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://xxx.xxx.xxx.xxx/")
.build();
//Create API service
RetrofitService service = restAdapter.create(RetrofitService.class);
//Invoke method
service.updateUser(
user.getUserId(),
user.getUserToken(),
mFirstName.getText().toString(),
mLastName.getText().toString(),
new Callback<JSONObject>() {
#Override
// user remains null!
public void success(JSONObject jsonObject, Response response) {
Toast.makeText(ProfileMe.this, "Profile Updated", Toast.LENGTH_SHORT).show();
Log.d("succes", "Success!");
}
#Override
public void failure(RetrofitError error) {
Log.d("failure", "Failed");
}
});
}
});
The above code works and the user's profile is updated. However the JSONObject in the onSuccess remains null.
I've been using Gson until now and I would do something like this:
//update user with new information
User user = gson.fromJson(responseData,User.class);
How do I do this with Retrofit?
EDIT
Response from the server returns a JSONObject. I changed the code above to satisfy those requirements but I am still returned a null JSONObject
Change to this:
public interface RetrofitService {
#FormUrlEncoded
#POST("/profile/update")
public void updateUser(
#Field("user_id") String userId,
#Field("user_token") String userToken,
#Field("first_name") String firstName,
#Field("last_name") String lastName,
Callback<User> callback);
}
You need to set in the callback what you are expecting to receive in the response. If the WS returns a User object you need to set that in the callback
Make sure that your rest has a Object as return (Json formatter).
You need change your code to this:
public interface RetrofitService {
#FormUrlEncoded
#POST("/profile/update")
public void updateUser(
#Field("user_id") String userId,
#Field("user_token") String userToken,
#Field("first_name") String firstName,
#Field("last_name") String lastName,
Callback<User> callback);
}
Retrofit uses Gson by default to convert HTTP bodies to and from JSON.
If you want to specify behavior that is different from Gson's defaults
(e.g. naming policies, date formats, custom types), provide a new Gson
instance with your desired behavior when building a RestAdapter. Refer
to the Gson documentation for more details on customization.
Edited
If your server returns something like this:
{
"user_id": "21q3123"
"user_token":"asd2334rter"
"first_name" : "User Test"
"last_name" : "user last name"
}
On your Android client you need to have something like this also
public class User {
String user_id;
String user_token;
String first_name;
String last_name;
//Getter and Setters
}
Retrofit by default use Gson to parser all requests.
See here a good example of Paser.com and Retrofit:
Android-Retrofit-Example

Categories

Resources