byte[] to string return null Android - java

i spend a lot of time to search how resolve my problem but stil unsuccessful, so i hop some one could help me.
I make my app with android studio:
i finish my page with login and httm request (100% working to conect and creat new account) and now i trying to make Get request to my server and get username rerver turn my array of bytes that i try to cast on string and in obtain just null "".
there is my code:
mainActivity.java
Button b = (Button)findViewById(R.id.b2);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SyncHttpClient client = new SyncHttpClient();
RequestParams params = new RequestParams();
params.put("email", "test3#t.com");
// Handle request
client.get("https://......../user/get/", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
System.out.println("response ----" + response);
String res = new String(response); //convetion Byte[] to String that i use
Context context = getApplicationContext();
Toast.makeText(context, res, Toast.LENGTH_SHORT).show();
System.out.println("res ----" + res);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
System.out.println("errorResponse -----"+errorResponse);
String res = new String(errorResponse);
Context context = getApplicationContext();
// Toast.makeText(context, res, ast.LENGTH_SHORT).show();
System.out.println("ERROR--" + res);
}
});
}});
Server side it's look like this :
views.py
def get_users(req):
"""
Use url :
https://...../user/get/
With arguments :
?email=EMAIL
"""
email = req.GET.get('email')
if email is not None:
exists = User.objects.filter(email=email)
if len(exists) == 0:
return HttpResponse("Error invalid email !")
else:
res = "%s:%s" %(exists[0].username, exists[0].points)
return HttpResponse(exists[0].username)
else:
return HttpResponse("Missing information !")
And that what i obtain on Android Monitor:
I/System.out: response------[B#4136b800
I/System.out: res --------
ass you can see after covertion i have just NULL .
Can Someone help me plz

Related

cz.msebera.android.httpclient.client.HttpResponseException: Unauthorized

Hello I'm trying to build a Clima app and I'm Using OpenWeatherMap Api
to retrieve weather data from the internet.
When I try the app on a physical device, I got this message error:
cz.msebera.android.httpclient.client.HttpResponseException: Unauthorized
I tried to generate a new API key but the same problem.
// TODO: Add letsDoSomeNetworking(RequestParams params) here:
protected void letsDoSomeNetworking(RequestParams params) {
AsyncHttpClient client = new AsyncHttpClient();
client.get(WEATHER_URL, params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode ,Header[] header , JSONObject response){
Log.d("Clima", "onSuccess: " + response.toString());
}
public void onFailure (int statusCode , Header[] headers , Throwable e , JSONObject response){
Log.d("Clima", "Onfailure: " + statusCode);
Log.d("Clima", "fail: " + e.toString());
Toast.makeText(WeatherController.this, "requestFialed " , Toast.LENGTH_SHORT).show();
}
});
}
i think it s highly like you didn't change this variable
final String APP_ID = "e****************************a"; on the weathercontroller.java
you're supposed to write yout own app_id , you can your own key by signing up at
http://api.openweathermap.org/ , you will get the app_id on your email and the key will be activated within 1hour or 2 . best of luck buddy!

Loopj Post method failure - error while trying to send post JSON

I am working in an android application that has to send user email through post method. The api endpoint is at https://api-iddog.idwall.co/ when i already run some tests and was able to GET values from here. Im using Loopj Library.
However, i've been tasked with using this endpoint:
https://api-iddog.idwall.co/signup
The documentation guide shows that i need to construct the POST method using the following parameters:
using Content-Type: application/json header
and the post URL should be something like:
Api Post Doc
With all that in mind, i got the create a method called attempPost(). On this method im creating the AsyncHttpRequest object, RequestParams object and storing the valid e-mail typed by the user.
private void attempPost() {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
String url = "https://api-iddog.idwall.co/signup";
String userEmail = userEmailView.getText().toString();
JSONObject jsonEmail = new JSONObject();
try {
jsonEmail.put("email", userEmail);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Dog", " " + jsonEmail.toString());
params.put("-d", jsonEmail);
client.addHeader("Content-Type", "application/json");
client.post(url, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d("Dog", "onSucess" + responseBody.toString());
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.e("Dog", "" + error.toString());
}
});
}
This method is called in a OnclickListener, and the log is returning a message called BadRequest and Status Code 400. I already tried to apply some code examples from Loopj doc but i didnt work. Can someone give me an insight in what i am doing wrong ? From what i can gather the success response should be a String(Token) and i need this token to complete the project.
EDIT.
I worked a little more through documentation and other examples here on Stack and i found this: POSTing JSON/XML using android-async-http (loopj)
In the accepted answer there is an example on how to post JSON.
Then i made a few changes in my attempPost method.
private void attempPost() {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
String url = "https://api-iddog.idwall.co/signup";
String userEmail = userEmailView.getText().toString();
JSONObject jsonParams = new JSONObject();
try {
jsonParams.put("email", "your#email.com");
} catch (JSONException e) {
e.printStackTrace();
}
client.post(getApplicationContext(), url, jsonParams, "application/json", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d("Dog", "onSucess" + responseBody.toString());
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.e("Dog", "" + error.toString());
Log.e("Dog", "status code " + String.valueOf(statusCode));
}
});
}
But Android Studio is telling me to convert jsonParams into a entity. In the example i got from stack its uses the following code to achieve that:
StringEntity entity = new StringEntity(jsonParams.toString());
However my android studio gets an horror that says:
Unhandled exception : java.io.UnsupportedEncodingException,
Until this moment i could not figure a way to solve this.
I managed to make it work, the API its now returning a proper response and status code 200. I converted the JsonObject into a ByteArrayEntity since the StringEntity was not an option.
private void attempPost() {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
String userEmail = userEmailView.getText().toString();
JSONObject jsonParams = new JSONObject();
try {
jsonParams.put("email", userEmail);
} catch (JSONException e) {
e.printStackTrace();
}
ByteArrayEntity be = new ByteArrayEntity(jsonParams.toString().getBytes());
//TODO create a class to handle JSON post, getmethods and parse token value
client.post(getApplicationContext(), API_URL, be, "application/json", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.d("Dog", "onSucess " + response.toString());
Log.d("Dog", "status code " + String.valueOf(statusCode));
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
Log.e("Dog", "" + errorResponse.toString());
Log.e("Dog", "status code " + String.valueOf(statusCode));
}
});
}

How do i send Delete request using Volley with Json object as a parameter?

My put method is working fine, but just changing the put request to Delete then its not working,, I tried even by sending its header. but still not working. I even tried Json object to set the parameter. Thanks in advance.
StringRequest stringRequest = new StringRequest(Request.Method.DELETE, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("blalala", response);
String qtyReserved1 = response.toString();
Toast.makeText(mContext, "ok" + qtyReserved1, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mContext, "not ok" + username + Integer.toString(inventoryId), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("screen_name", username);
params.put("inventory_id", Integer.toString(inventoryId));
params.put("pending", "true");
return params;
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
MySingleton.mySingletonInstance(mContext.getApplicationContext()).addToRequestque(stringRequest);
Volley library don't send body when you using DELETE method. You can try other library. I am providing you an example by using loopj library
Add dependency in your gradle
compile 'com.loopj.android:android-async-http:1.4.9'
Request your web Api
RequestParams requestParams = new RequestParams();
requestParams.put("screen_name", "mariyam.shimaanath");
requestParams.put("inventory_id", 19);
requestParams.put("pending", true);
String url="192.168.4.31/api/canteen/cart";
new AsyncHttpClient().delete(url, requestParams, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
String rs = new String(responseBody);
// do whatever you want
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
After lots of research, thank God I'm managed to solve the problem,, Not exactly solved the problem had in Delete request in Volley. But, I had to changed the method i need to request from server side. I changed the request to post method, I know it might not be good practice and solution, but now i managed to delete from sever. thats what i need.

Android volley. Get data from the header of the HTTP response

I am making http requests to my REST server. As a response I get the JSON body. But I need to get also a parameter from the response header, as I keep the user token in it. I have looked at a lot of posts on Stack Overflow for similar questions, but I they don't seem to have helped me. I want to make a JSON request, and get the body and headers form the response. How can I do it? Here is my code:
Please don't mark the question as duplicate, as I have not found any example where I can retrieve both: the response header and the response body. For the existing questions, users get only the headers
JsonObjectRequest req = new JsonObjectRequest(AppConfig.URL_LOGIN, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response.toString());
hideDialog();
try {
JSONObject jObj = response;
String uid = jObj.getString("_id");
String name = jObj.getString("fullName");
String email = jObj.getString("email");
// Inserting row in users table
db.addUser(name, email, uid);
Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(
LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
String toastError = "Response code: " + networkResponse.statusCode;
Toast.makeText(getApplicationContext(),
toastError, Toast.LENGTH_LONG).show();
hideDialog();
}
});
You can't do that using JsonObjectRequest. You should extend the Request class and implement parseNetworkResponse() method which provides access to low-level NetworkResponse object. Downside is of course that you have to re-implement JSON parsing as well, but this is not really a big deal.
Something like:
public class HeaderAwareJsonRequest extends Request<Pair<JSONObject,Map>> {
protected Response.Listener<Pair<JSONObject,Map>> listener;
public HeaderAwareJsonRequest( int method, String url, Response.Listener<Pair<JSONObject,Map>> listener, Response.ErrorListener errorListener ) {
super( method, url, errorListener );
this.listener = listener;
}
#Override
protected Response<Pair<JSONObject,Map>> parseNetworkResponse( NetworkResponse response ) {
try{
String jsonString = new String( response.data, HttpHeaderParser.parseCharset( response.headers ) );
// pair contains the json body and headers
Pair pair = new Pair( new JSONObject( jsonString ), response.headers );
return Response.success( pair, HttpHeaderParser.parseCacheHeaders( response ) );
}catch( Exception e ){
return Response.error( new ParseError( e ) );
}
}
}
then in the calling code:
HeaderAwareJsonRequest req = new HeaderAwareJsonRequest(
Request.Method.GET,
AppConfig.URL_LOGIN,
new Response.Listener<Pair<JSONObject,Map>>() {
#Override
public void onResponse(Pair<JSONObject,Map> response) {
JSONObject jObj = response.first;
Map headers = response.second;
String someHeader = headers.get( "aaaaa" );
...
}
},
new Response.ErrorListener() {...}
);

Not finding RequestParams with Rest service

I'm writing an android application which uses rest services for user regitration and more but running into trouble with my login service. for some reason the requestparams i put into my service call on android side are not being found within my rest service.
could anny 1 tell me what i'm doing wrong or link to a guide which explains how to solve this problem?
Relevant android functions:
public void loginUser(View view) {
// Get username and password values
String username = usernameEdit.getText().toString();
String password = passwordEdit.getText().toString();
// Instantiate Http Request Param Object
RequestParams params = new RequestParams();
// Check if username & password is not null
if(Utility.isNotNull(username) && Utility.isNotNull(password)) {
// Http parameters
params.put("username", username);
params.put("password", password);
invokeWS(params);
} else {
Toast.makeText(getApplicationContext(), "Vul een gebruikersnaam en of " +
"wachtwoord in", Toast.LENGTH_LONG).show();
}
}
// Method that performs RESTful webservice invocations
public void invokeWS(RequestParams params) {
// Make RESTful webservice call using AsyncHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://10.0.2.2:8080/NTR_application/rest/session", params, new AsyncHttpResponseHandler() {
// When the response returned by REST has Http response code '200'
#Override
public void onSuccess(String response) {
Toast.makeText(getApplicationContext(), "You are successfully logged in!" + response, Toast.LENGTH_LONG).show();
// Gets an JSON object with user Data
// Write user Data to SQLite
User user = new Gson().fromJson(response, User.class);
db.addUser(user);
// Navigate to Home screen
navigatetoHomeActivity();
}
// When the response returned by REST has Http response code other than '200'
#Override
public void onFailure(int statusCode, Throwable error,
String content) {
Toast.makeText(getApplicationContext(), "ERROR!" + content + error + statusCode, Toast.LENGTH_LONG).show();
}
});
}
and the rest services which is called :
#Path("/session")
public class UserService {
private Controller controller = new Controller();
#POST //Post so you can't see the information in the browser history easily
#Produces(MediaType.APPLICATION_JSON)
public Response authenticate(#QueryParam("username") String username, #QueryParam("password") String password){
User user = null;
try {
user = controller.authenticate(username, password);
} catch (NoSuchAlgorithmException | SQLException e) {
System.out.println("Authentication caught an exception; failed for: " + username);
e.printStackTrace();
}
if (user != null){
String json = new Gson().toJson(user);
return Response.status(200).entity(json).build();
} else {
return Response.status(401).entity("Username and/or password is incorrect").build();
}
}
}
Mistake was obvious once i saw it, since i use a #POST i need to use #FormParam instead of #QueryParam.
tutorial i used to write these methods used #GET to login which is insecure.

Categories