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..
Related
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);
}
I'm new to Retrofit. How can I send param and get Json from bellow url ?
http://xxx:8087/courier.svc/login?username=jim&password=123456
I need to a link for tutorial .
This code is in my MainActivity :
private void loadJSON(String username, String password) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.8.11:8087/sample.svc/")
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface_Login request = retrofit.create(RequestInterface_Login.class);
Call<JSONResponseLogin> call = request.getJSON(username, password);
call.enqueue(new Callback<JSONResponseLogin>() {
#Override
public void onResponse(Call<JSONResponseLogin> call, Response<JSONResponseLogin> response) {
JSONResponseLogin jsonResponse = response.body();
data = new ArrayList<>(Arrays.asList(jsonResponse.getLogin()));
}
#Override
public void onFailure(Call<JSONResponseLogin> call, Throwable t) {
Log.d("Error", t.getMessage());
}
});
}
My ModelLogin :
public class ModelLogin {
private String username;
private String password;
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
My RequestInterface_Login :
public interface RequestInterface_Login {
#GET("/login/{username}/{password}")
Call<JSONResponseLogin> getJSON(#Path("username") String username, #Path("password") String password);
}
My JSONResponseLogin :
public class JSONResponseLogin {
private ModelLogin[] login;
public ModelLogin[] getLogin() {
return login;
}
}
But get me NullPointerException!
I get json from service same bellow :
{"Key":null,"Response":1}
Before you get call the retrofit you can just print the URL and then you can load URL in browser and see what response is coming you can add log by bellow line before call.enqueue(new Callback<JSONResponseLogin>()
Log.e(TAG, "API URL: " + call.request().url());
Check your response
And let me know I will help you ... coz i am using retrofit in my 3 projects
Do like this ...in interface
#GET("/courier.svc/login?)
Call<JSONResponseLogin> getJSON(#Query("username") String username,
#Query("password") String password);
and remove it from base .baseUrl("http://192.168.8.11:8087")
I am writing this post on 'Retrofit in android' using our latest Retrofit library, This plugin can be be used to Integrate Retrofit to your project.
Before using reftrofit, we just need to follow some steps to add QAssist Plugins in Android studio which will reduce your efforts of Webservices integration.
1.Add (QAssist - Android Studio Plugin) Android plugin in your Android studio. ( https://github.com/sakkeerhussain/QAssist ).:-
2.When we done with the plugin then we need to restart our Android studio.
3.Check your Android studio Menubar You can find "QAssist".
4.Click on that and Start with Retrofit Integrate.
5.Now we need :
- BaseUrl of Web Api's
- All Api's en points.
- Sample request and Response of All request.
- After completing these steps your reftrofit(QAssist/retrofit package is genrated inside Project).
6.You can find A Class and One Interface inside that Package.
7.The interface contain all the endpoints detail and Class will cotain the Retrofit connection details.
8.We just need to add a small code to access and Api and Parse that Api' response to Data model.
9.Use this sample function to call Api.
private void demoRetroFitCall() {
APIService apiService = RetrofitManager.getInstance(this);
//APIService apiService = RetroFitApiClient.getClient().create(APIService.class);
Call<ModelData> call = apiService.TestGet();
call.enqueue(new Callback<ModelData>() {
#Override
public void onResponse(Call<ModelData> call, Response<ModelData> response) {
Log.d("TAG", "Data recived in response.body");
}
#Override
public void onFailure(Call<ModelData> call, Throwable t) {
Log.e("TAG", t.toString());
}
});
}
56 - voda
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?
I have some custom POJO:
class CustomClass {
int x;
String str;
SecondCustomClass obj; //indicate it's not class of simple types
//etc...
}
I want to send instance of him from Android (Volley library) client to web service running on Spring-boot java application. Currently I know how to send data with URL params and return to client custom object. But I want also to send custom object.
Code in Android (I know that I need to use 3'rd parameter which is now null but I'm struggling get it work):
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
"BASE_URL?param1=param",
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
CustomClass result = new Gson().fromJson(response.toString(), CustomClass.class);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
volleyQueue.add(request);
Code in server:
EDIT: The solution to receive pojo is using #RequestBody
#RequestMapping("/webmethod")
public CustomClass webmethod(#RequestParam(value="obj_param") #RequestBody CustomClass obj) {
//work with obj
}
What do I need to put in Android side to get it work?
You have to use the JSON object inside the JSON object.Below is the sample. When you are request the Parameter with only one request.
This the Request JSON
{
"x":10,
"str":"MyName",
"SecondCustomClass":{
"id":10,
"title":"make it eassy"
}
}
This is the post parameter request from Android. Try this way.
For more details please use this link
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