Método Post retorna response code 400 no Android com Volley Singleton

24/06/2018

8

Eu criei duas classes customizadas de acordo com o que foi orientado por meu professor para fazer a requisição no servidor, mas estou recebendo um retorno 400 e não consigo descobrir a razão. Pesquisando, vi que pode ser algo relacionado ao cabeçalho, mas não sei como enviá-lo na minha requisição JSon customizada.

Este é o código do meu do meu código customizado para requisição de JsonObject:

[code=java]package com.example.sandrini.pokeagenda;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class CustomJSONObjectRequest extends JsonObjectRequest {

public CustomJSONObjectRequest(int method, String url, JSONObject jsonRequest,
Response.Listener<JSONObject> listener,
Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}

@Override
public RetryPolicy getRetryPolicy() {
return super.getRetryPolicy();
}
}
Este é o código da minha Request Queue:

package com.example.sandrini.pokeagenda;

import android.content.Context;

import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;

public class CustomVolleyRequestQueue {

private static CustomVolleyRequestQueue mInstance;
private static Context mCtx;
private RequestQueue mRequestQueue;

private CustomVolleyRequestQueue(Context context) {
//recebe o contexto da aplicação
//Assim a fila dura o ciclo de vida do app
mCtx = context;
mRequestQueue = getRequestQueue();
}

public static synchronized CustomVolleyRequestQueue getmInstance(Context context) {
if (mInstance == null) {
mInstance = new CustomVolleyRequestQueue(context);
}
//retorna uma instância da fila
return mInstance;
}

public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
//Cache 10MB
Cache cache = new DiskBasedCache(mCtx.getCacheDir(), 10 *1024);
Network network = new BasicNetwork(new HurlStack());
mRequestQueue = new RequestQueue(cache, network);
mRequestQueue.start();
}
return mRequestEste é o código da Activity onde estou tentando fazer a requisição:

package com.example.sandrini.pokeagenda;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonRequest;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.EmptyStackException;

public class CreateUserActivity extends AppCompatActivity implements Response.Listener, Response.ErrorListener {
private static final String REQUEST_TAG = "CreateUser";
Trainer trainer = new Trainer();
EditText loginCreateInput, emailCreateInput, pwdCreateInput;
Button createUserButton;
private RequestQueue mQueue;
JsonRequest jsonRequest;
ProgressBar progressBarCreateUser;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_user);

loginCreateInput = (EditText) findViewById(R.id.login_create_input);
emailCreateInput = (EditText) findViewById(R.id.email_create_input);
pwdCreateInput = (EditText) findViewById(R.id.pwd_create_input);
createUserButton = (Button) findViewById(R.id.create_user_button);
progressBarCreateUser = (ProgressBar) findViewById(R.id.progress_bar_create_user);

progressBarCreateUser.setVisibility(View.INVISIBLE);
}

@Override
protected void onStart() {
super.onStart();

createUserButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (loginCreateInput.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(), "Please, set a login", Toast.LENGTH_SHORT).show();
} else if (emailCreateInput.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(), "Please, set an email", Toast.LENGTH_SHORT).show();
} else if (pwdCreateInput.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(), "Please, set a password", Toast.LENGTH_SHORT).show();
} else {
String url = "http://192.168.25.6:8081/PokedexWS/webresources/pokews/poke/insert/trainer";
/*trainer.setUsername(loginCreateInput.getText().toString());
trainer.setEmail(emailCreateInput.getText().toString());
trainer.setPassword(pwdCreateInput.getText().toString());*/
trainer.setUsername("gato");
trainer.setEmail("gato");
trainer.setPassword("gato");

try {
JSONObject jsonObject;
Gson gson = new Gson();
String trainerToGson = gson.toJson(trainer);
jsonObject = new JSONObject(trainerToGson);
//String trainerToGson = "{\\\\"username\\\\":"+ "\\\\"" + trainer.getUsername()+ "\\\\"" + "," +
//"\\\\"email\\\\":"+ "\\\\"" + trainer.getEmail() + "\\\\"" + "," +
//"\\\\"username\\\\":"+ "\\\\"" + trainer.getPassword()+ "\\\\"" + "}";
//createUserButton.setText(trainerToGson);


mQueue = CustomVolleyRequestQueue.getmInstance(CreateUserActivity.this.getApplicationContext()).getRequestQueue();
jsonRequest = new CustomJSONObjectRequest(Request.Method.POST, url, jsonObject,
CreateUserActivity.this, CreateUserActivity.this);
jsonRequest.getHeaders();
mQueue.add(jsonRequest);
progressBarCreateUser.setVisibility(View.VISIBLE);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});

}

@Override
protected void onStop() {
super.onStop();
if(mQueue != null) {
mQueue.cancelAll(REQUEST_TAG);
}
}



@Override
public void onErrorResponse(VolleyError error) {
progressBarCreateUser.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(), "Register failed", Toast.LENGTH_LONG).show();
Log.e("erro400", error.getMessage().toString());
Log.e("erro400", error.getCause().toString());
Log.e("erro400", error.getStackTrace().toString());
}

@Override
public void onResponse(Object trainerObject) {
progressBarCreateUser.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(), "Registered successfully", Toast.LENGTH_LONG).show();
Intent intent = new Intent(CreateUserActivity.this, WelcomeTrainerActivity.class);
startActivity(intent);
finish();
Responder

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários. Para saber mais sobre o uso de cookies,
consulte nossa política de privacidade. Ao continuar navegando em nosso site, você concorda com a nossa política.

Aceitar