Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Leonardo Sandrini

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

Recommended Posts

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:

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 mRequestQueue;
}
}

Este é 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();
    }
}

Este é o meu 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) {
    }


}

Eu peguei um código java pra testar o WS e tá funcionando, só não estou conseguindo requisitar pelo 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());

    }

}

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por ILR master
      Pessoal, pergunta bem simples. Abaixo tenho o seguinte código:
       
      <script>
      function alerta()
      {
        if (window.confirm("Você realmente quer sair?")) {
          window.open("sair.html");
      }
      }
      </script>
       
      Funciona perfeitamente, só que está abrindo em outra janela e quero que abra na mesma janela.
       
      Alguém pode me ajudar?
    • Por Jack Oliveira
      Ola pessoal boa tarde
      estou tentando fazer um texto se mover dentro do input porem nao esta dando resultado que preciso
       
      Este é o codigo 
      <script type="text/javascript"> $(document).ready(function () { var frases = [{ 'elemento': $('input[name=search_string]'), 'frases': ["O que você está procurando?", "Buscar por: Academia, Barbearia, Churrascaria, Decoração, Escola, Farmácia, Gráfica, Imobiliaria, Lanchonete, Mecânica, Odontologia, Pizzaria...", "Faça sua busca por segmentos aqui.", "São mais de 3mil empresas para serem exploradas."] }]; animaInput(frases); }); </script>  
    • Por Rengavitp
      Boa noite pessoal!
       
      Estou fazendo um projeto web com spring boot e é a primeira vez que lido com imagens. Minha idéia é salvar imagens em uma pasta e depois recuperar essa imagem e mostrar, mas o problema que estou enfrentando é o seguinte, seu eu envio para o src do projeto na pasta imagens, eu até consigo acessar as imagens, mas preciso atualizar o projeto na IDE (isso vai acontecer em produção?) eu tentei salvar em uma pasta fora do source do projeto mas ai não consigo acessar. como devo fazer? fiz várias pesquisas, mas nenhuma me ajudou.
       
      Desde já agradeço.
    • Por Rengavitp
      Bom dia pessoal!

      Estou com o seguinte problema, tenho uma aplicação que funciona perfeitamente rodando na minha IDE (Spring Tool Suite) mas ao gerar o arquivo war e subir a aplicação no tom cat ele não funciona, mas apenas erro 404, abri o war e todos os arquivo estão lá, já tem seguir tudo quando e tutorial com problemas semelhantes mas nenhum resolveu. Abaixo mais informações,.

      Versão do java na aplicacao 11
      Versão do jva no servidor 11
      Versão do tomcat no servidor 8.5.55
       
      minha classe principal
      package br.com.masterplastfitas; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication public class MasterApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(MasterApplication.class, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(MasterApplication.class); } } meu pom.xml
      <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.2</version> <relativePath /> <!-- lookup parent from repository --> </parent> <groupId>masterplast</groupId> <artifactId>Master</artifactId> <version>2.0</version> <packaging>war</packaging> <name>Master</name> <description>Aplicação web </description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId>mssql-jdbc</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity5</artifactId> </dependency> <dependency> <groupId>org.mindrot</groupId> <artifactId>jbcrypt</artifactId> <version>0.4</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.0</version> </dependency> </dependencies> <build> <plugins> <!-- <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> --> </plugins> </build> </project>  
    • Por Stephhany909
      While trying to persist an object with an attribute of type Point, defined as follows:
       
      @Entity @Table(name = "event") public class Event { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private long id; @Column(columnDefinition = "POINT") private Point coordinate; } I'm getting the error Data truncation: Cannot get geometry object from data you send to the GEOMETRY field.
      The corresponding database table is defined as follows:
       
      create table event ( id bigint not null auto_increment, coordinate POINT, primary key (id) ) engine= InnoDB; What am I missing?
       
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.