I've created two custom classes according to what my teacher instructed to do the request on the server, but I'm getting a 400 return and I can not figure out the reason. Searching, I saw that it may be something related to the header, but I do not know how to send it in my custom JSon request.
This is my code from my custom code for JsonObject request:
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();
}
}
This is the code for my 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 mRequestQueue;
}
}
This is the Activity code where I am trying to make the request:
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();
}
}
This is my Web Service:
package ws;
import com.google.gson.Gson;
import dao.PokemonDAO;
import dao.TrainerDAO;
import java.util.ArrayList;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import model.Pokemon;
import model.Trainer;
/**
* REST Web Service
*
* @author sandrini
*/
@Path("pokews")
public class PokedexWebService {
PokemonDAO pokemonDAO = new PokemonDAO();
TrainerDAO trainerDAO = new TrainerDAO();
@Context
private UriInfo context;
/**
* Creates a new instance of PokedexWebService
*/
public PokedexWebService() {
}
/**
* Retrieves representation of an instance of teste.GenericResource
* @return an instance of java.lang.String
*/
@GET
@Produces(MediaType.APPLICATION_XML)
public String getXml() {
//TODO return proper representation object
throw new UnsupportedOperationException();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("poke/list")
public ArrayList<Pokemon> pokeList() {
return pokemonDAO.listPokemon();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("poke/fetch/{id}")
public Pokemon pokeFetch(@PathParam("id") int id) {
return pokemonDAO.fetchPokemon(id);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("poke/isFavorite/{id}")
public String pokeIsFavorite(@PathParam("id") int id) {
return pokemonDAO.isFavorite(id);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("poke/login/{login}/{pwd}")
public Trainer pokelogin(@PathParam("login") String login, @PathParam("pwd") String pwd) {
return trainerDAO.authUser(login, pwd);
}
@DELETE
@Path("poke/delete/{id}")
public boolean delete(@PathParam("id")int id) {
return pokemonDAO.deletePokemon(id);
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("poke/insert")
public boolean pokeInsert(String content) {
Gson gson = new Gson();
Pokemon pokemon = (Pokemon) gson.fromJson(content, Pokemon.class);
return pokemonDAO.insertPokemon(pokemon);
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("poke/insert/trainer")
public boolean trainerInsert(String content) {
Gson gson = new Gson();
Trainer trainer = (Trainer) gson.fromJson(content, Trainer.class);
return trainerDAO.insertTrainer(trainer);
}
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Path("poke/update")
public boolean pokeUpdate(String content) {
Gson gson = new Gson();
Pokemon pokemon = (Pokemon) gson.fromJson(content, Pokemon.class);
return pokemonDAO.updatePokemon(pokemon);
}
/**
* PUT method for updating or creating an instance of GenericResource
* @param content representation for the resource
*/
@PUT
@Consumes(MediaType.APPLICATION_XML)
public void putXml(String content) {
}
}
I've got a java code to test the WS and it works, I just can not get the android:
package acessorest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.lang.ProcessBuilder.Redirect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
/**
*
* @author marcelosiedler
*/
public class HttpExemplo {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
HttpExemplo http = new HttpExemplo();
Gson gson = new Gson();
Pokemon pokemon = new Pokemon();
java.lang.reflect.Type pokemonType = new TypeToken<Pokemon>() {
}.getType();
String chamadaWS = "http://192.168.25.6:8081/PokedexWS/webresources/pokews/poke/insert/trainer";
Trainer trainer = new Trainer();
trainer.setUsername("quadrado");
trainer.setEmail("quadrado");
trainer.setPassword("quadrado");
//System.out.println(gson.toJson(trainer));
String trainerToGson = gson.toJson(trainer);
/*String trainerToGson = "{\"username\":"+ "\"" + trainer.getUsername()+ "\"" + "," +
"\"email\":"+ "\"" + trainer.getEmail() + "\"" + "," +
"\"password\":"+ "\"" + trainer.getPassword()+ "\"" + "}";*/
//System.out.println(trainerToGson);
//String retorn = http.sendGet(chamadaWS, "DELETE");
//pokemon = gson.fromJson(json, pokemonType);
//System.out.println(retorn);
http.sendPost(chamadaWS,trainerToGson, "POST");
}
// HTTP GET request
private String sendGet(String url, String method) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod(method);
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
return response.toString();
}
// HTTP POST request
private void sendPost(String url, String parameters, String method) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod(method);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = parameters;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
}