Retrofit updating class PUT error code 301 - android

Maybe this is a silly question but I've been stucked on this for a while. I'm implementing some methods for a restApi. I'm using retrofit and I'm trying to update a client information. To do an update I'm using PUT method but I don't know why I'm always getting a 301 CODE and I can't update the information. Here is my code, thank you for everything.
public interface ClientInterface {
#GET("/clients/{clientParam}")
public Client fetchClient(#Path("clientParam") String client);
#GET("/clients/")
public void fetchAllClients(Callback<List<Client>> callback);
#POST("/clients/")
public void newClient(#Body Client client, Callback<Client> callback);
#PUT("/clients/{clientParam}/")
public void updateClient(#Path("clientParam") String cod, #Body Client client,Callback<Client> callback);
}
After that I use the update method in the following way
RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(Utils.getURLPreferences(DatosClienteActivity.this)).build();
ClientInterface clientRestInter = restAdapter.create(ClientInterface.class);
Client clientsUpdate = new Client();
//Fetch data into clientsUpdate object
clientRestInter.updateClient(codClient, clientsUpdate, new Callback<Client>() {
#Override
public void success(Client client, retrofit.client.Response response) {
}
#Override
public void failure(RetrofitError error) {
error.printStackTrace();
}
});
EDIT:
If I use volley against the same URL it's working perfectly...
RequestQueue queue = Volley.newRequestQueue(this);
final JSONObject jsonObject = new JSONObject();
try {
//Construct jsonObject
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest req = new JsonObjectRequest(Request.Method.PUT, URL, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
error.printStackTrace();
}
});
queue.add(req);

Finally I solved it.
The problem was that we had two different Client objects and the one that you fetch is the one that you must change and use it to upload with PUT.
I hope that this help somebody.

Related

volley authentication errors when attempting to push to the server

I am developing an android app in which I have created a custom API for database. I am using volley for HTTP request. I am getting "com.android.volley.AuthFailureError" error on my onErrorResponse. I have checked the JSONObject in the debugger and it's valid.Moreover, I am using "application/json" in the header.
I am unable to find a way to fix this error. Here is the JsonRequest.
Here I am trying to use JSONRequest:
public void jsonPOST(String jsonInput) {
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
String URL = "http://Servername:8080/users";
try{
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(jsonInput),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
queue.add(req);
}
catch (JSONException error){
String output = error.toString();
}
}
I have checked the JSONObject in the debugger and it's valid. I am also checked the network firewall but it also seems fine

Multiple object request using Volley Android

I want to call API Using Volley. There is an Multiple object Request So i don't Know Proper way. I was tried to code as below.But it does not give me Response.So can Anyone help me???
MainActivity
public void getJsonResponsePost(){
JSONObject jsonData = new JSONObject();
JSONObject json = new JSONObject();
/*{"data":{"lang_type":"1","keyword":"","latitude":23.022499999999997,"longitude":72.57139833333333,"category":6}}*/
try {
jsonData.put("data",json);
json.put("lang_type","1");
json.put("keyword","");
json.put("latitude",23.022499999999997);
json.put("longitude",72.57139833333333);
json.put("category",6);
Log.d("TAG",jsonData.toString());
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, json, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response)
{
Log.d("String Response :",response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(" Error getting :",error.toString());
}
});
jsonObjectRequest.setTag(REQ_TAG);
requestQueue.add(jsonObjectRequest);
}
I get the following response
String Response :: {"status":"0","message":"Please pass the language type."}
Can you try this?
try {
json.put("lang_type","1");
json.put("keyword","");
json.put("latitude",23.022499999999997);
json.put("longitude",72.57139833333333);
json.put("category",6);
jsonData.put("data",json);
Log.d("TAG",jsonData.toString());
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonData, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response)
{
Log.d("String Response :",response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(" Error getting :",error.toString());
}
});

Volley Get Request: onResponse is never called

im pretty new to Android Studio and I'm trying to build a Get Request using Volley, the Server response is a JsonObject. I tested the code with breakpoints but I wonder why I don't jump into onResponse or why it won't work.
Here's my Code of the Get Method:
public Account GetJsonObject(String urlExtension, String name, Context context) {
String baseURL = "myurl.com/api";
baseURL += urlExtension + "/" + name;
// url will look like this: myurl.com/api/user/"username"
final Account user = new Account("","");
//Account(name, email)
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(context);
JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.GET, baseURL,null,
new Response.Listener<JSONObject>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = response.getJSONObject("userObject");
String username = obj.getString("Username");
String email = obj.getString("Email");
user.setUsername(username);
user.setEmail(email);
}
catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObject);
return user;
}
As #GVillavani82 commented your onErrorResponse() method body is empty. Try to log the error like this
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ERROR", "Error occurred ", error);
}
}
Make sure that you have the below permission set in AndroidManifest.xml file and the api URL is proper.
<uses-permission android:name="android.permission.INTERNET"/>
And JsonObjectRequest class returns Asynchronous network call class. Modify your code like below.
// remove Account return type and use void
public void GetJsonObject(String urlExtension, String name, Context context) {
....
.... // other stuffs
....
JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.GET, baseURL,null,
new Response.Listener<JSONObject>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONObject response) {
processResponse(response); // call to method
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ERROR", "Error occurred ", error);
}
});
requestQueue.add(jsonObject);
}
Now create another method like below
private void processResponse(JSONObject response) {
try {
final Account user = new Account("","");
JSONObject obj = response.getJSONObject("userObject");
String username = obj.getString("Username");
String email = obj.getString("Email");
user.setUsername(username);
user.setEmail(email);
} catch (JSONException e) {
e.printStackTrace();
}
}

Android JSON VOlley

Good Day, I would like to get data from this url, and I have problems with onResponse method implementation:
I have something like this:
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://horoscope-api.herokuapp.com/",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
//The Problem is here
JSONArray jsonArray = response.getJSONArray("");
String author = jsonArray.getString(0);
textView.setText(author);
}catch(JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
requestQueue.add(jsonObjectRequest);
}
I don`t understand how to implement onResponse method correctly, I know that I must to get string from array or object, but data from link make me problems to understand what is it object or array, can you write me how to get author field from this url.
Thank you
Since the response in your link is JSONObject, you only need to do the following inside onResponse:
String author = response.getString("author");
textView.setText(author);
Hope this helps!
The response that you are getting is not a JSONArray but is a JSONObject. You could try the below code and see if you are able to get the author.
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://horoscope-api.herokuapp.com/",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String author = response.get("author");
textView.setText(author);
}catch(JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
requestQueue.add(jsonObjectRequest);
}
Hope this helps.
The data from link is JSONObject not JSONArray. Call response.getString("author"); to get author string.
try{
String author = response.getString("author");
} catch(JSONException e) {
e.printStackTrace();
}

Accessing volley response in another class/method

I am beginning in my journey in Android development so might be doing this all wrong. I am trying to get a set of data using Volley and display it which is ok.
The next step I need to do is use the data to make further requests.
The first request gets a list of sports teams.
I then want to make a request for each team to get the players.
Ideally what I'd like to do is make the first request and return the JSONobject to be used with another class. I have no idea how i would do this.
teamData.getTeams(
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//i want to get this out somehow
JSONObject thing = response;
}//end on response
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Show error or whatever...
}
});
I'm happy to expand on this if need be.
Volley is enqueuing the request so it fires a request after the older one has returned success or error.
So you can enqueue a new request in the success of the older.
Exemple : in your response of your team request you add a new request as you did JSONObject thing = response;
This is an exemple of mine witch imports multiple projects and then imports each project infos:
public void importProjects() {
Response.Listener<JSONArray> jsonArrayResponseListener;
String url = Globals.getApiBaseUrl() + GET_PROJECTS_URL;
jsonArrayResponseListener = new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
ArrayList<Project> projects = MyJsonParser.getInstance().parseProjects(response);
if (projects.size() > 0) {
for (Project p : projects) {
importProject(p); //####### HERE IS THE KEY :: this methode is the same of this one. It calls other volley request.#######//
}
}
} catch (Exception e) {
Log.e("SyncRngine", "THIS IS AN ERROR");
e.printStackTrace();
}
}
};
Response.ErrorListener responseError;
responseError = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
};
url = formatUrl(url, params);
Log.i("URL IMPORT PROJECTS", url);
MyVolleyJsonArrayRequest customRequest = new MyVolleyJsonArrayRequest(Request.Method.GET, url, jsonArrayResponseListener, responseError);
MyVolley.getInstance(activity.getApplicationContext()).addToRequestQueue(customRequest);
}
And now the défénition of importProject(Project p) :
public void importProject(final Project project) {
String url = Globals.getApiBaseUrl() + GET_PROJECT_URL;
Response.Listener<JSONArray> jsonArrayResponseListener;
jsonArrayResponseListener = new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
useProjectInfos(response);
} catch (Exception e) {
e.printStackTrace();
}
}
};
Response.ErrorListener responseError;
responseError = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
};
url = url + "/" + project.getProjectID();
url = formatUrl(url, params);
MyVolleyJsonArrayRequest customRequest = new MyVolleyJsonArrayRequest(Request.Method.GET, url, jsonArrayResponseListener, responseError);
MyVolley.getInstance(activity.getApplicationContext()).addToRequestQueue(customRequest);
}

Categories

Resources