DELETE and PUT in AndroidStudio with HttpUrlConnection

0

I have a REST API from a user database made in NodeJS, the address to use the GET method is http://localhost:3000/users/ the method DELETE and PUT receive a parameter that is concatenated in the same address, http://localhost:3000/users/2 where the last one is the id of the user that I want to delete or edit.

I am developing the application on Android using HttpUrlConnection and Asynctask , but it is difficult for me in that part, I can not send the parameter in the url.

UserModel.java

package muse.pe.com.s13s01pedroso.model;

public class UsuarioModel {

private int id;
private String username;
private String email;
private String password;
private String create;
private String updated;

public UsuarioModel() {
}

public UsuarioModel(int id) {
    this.id = id;
}

public UsuarioModel(int id, String username, String email, String password, String create, String updated) {
    this.id = id;
    this.username = username;
    this.email = email;
    this.password = password;
    this.create = create;
    this.updated = updated;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getCreate() {
    return create;
}

public void setCreate(String create) {
    this.create = create;
}

public String getUpdated() {
    return updated;
}

public void setUpdated(String updated) {
    this.updated = updated;
}
}

UserController.java

package muse.pe.com.s13s01pedroso.controler;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import muse.pe.com.s13s01pedroso.model.UsuarioModel;

public class UsuarioController {

static final String urlWS = "http://192.168.1.34:3000/users/";

//POST
public JSONObject post(UsuarioModel nuevo){
    JSONObject jsonResult= new JSONObject();
    try {
        URL obj = new URL(urlWS);
        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
        conn.setRequestMethod("POST"); //type: POST, PUT, DELETE
        conn.setDoOutput(true);
        conn.setRequestProperty("Accept", "application/json");
        conn.setUseCaches(false);
        conn.setRequestProperty("Accept-Encoding", "gzip");
        conn.setRequestProperty("Content-Type", "application/json");

        OutputStreamWriter osw =
                new OutputStreamWriter(conn.getOutputStream(),"UTF-8");

        JSONObject uu = new JSONObject();
        uu.put("username", nuevo.getUsername());
        uu.put("password", nuevo.getPassword());
        uu.put("email", nuevo.getEmail());

        osw.write(uu.toString()); // CONVERT CLASS A JSONOBJECT
        osw.flush();
        osw.close();
        //TODO - RESULTADO
        BufferedReader in =
                new BufferedReader(
                        new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String inputLine;
        StringBuffer html = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            html.append(inputLine);
        }
        in.close();
        System.out.println("URL Content... \n" + html.toString());

    }catch (Exception e){
        e.printStackTrace();
    }
    return jsonResult;
}

//DELETE
public JSONObject detete(UsuarioModel id){
    JSONObject jsonResult= new JSONObject();
    try {
        URL obj = new URL(urlWS + id);
        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
        conn.setRequestMethod("DELETE"); //type: POST, PUT, DELETE
        conn.setDoOutput(true);
        conn.setRequestProperty("Accept", "application/json");
        conn.setUseCaches(false);
        conn.setRequestProperty("Accept-Encoding", "gzip");
        conn.setRequestProperty("Content-Type", "application/json");

        System.out.println("Response code: " + conn.getResponseCode());

        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line, responseText = "";
        while ((line = br.readLine()) != null) {
            System.out.println("LINE: "+line);
            responseText += line;
        }
        br.close();
        conn.disconnect();
        }catch (Exception e){
            e.printStackTrace();
    }
    return jsonResult;
}
}

RemoveActivity.java

package muse.pe.com.s13s01pedroso.view;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONObject;

import muse.pe.com.s13s01pedroso.R;
import muse.pe.com.s13s01pedroso.controler.UsuarioController;
import muse.pe.com.s13s01pedroso.model.UsuarioModel;

public class EliminarActivity extends AppCompatActivity {

EditText objEliminar;
Button objBtnEliminar;

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

    objEliminar = findViewById(R.id.tvEliminar);
    objBtnEliminar = findViewById(R.id.btnEliminar);
    objBtnEliminar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
}

public class myAsync extends AsyncTask<String,String,JSONObject> {
    @Override
    protected JSONObject doInBackground(String... strings) {
        UsuarioController ctl = new UsuarioController();
        UsuarioModel item = new UsuarioModel();
        return ctl.detete(item);
    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onPostExecute(JSONObject s) {
        Toast.makeText(EliminarActivity.this,s.toString(),Toast.LENGTH_LONG).show();
    }
}
}
    
asked by Wil Pedroso 16.12.2017 в 22:29
source

1 answer

-1

Try to do it with a list of NameValuePair like this:

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", nuevo.getUsername()));
        params.add(new BasicNameValuePair("password", nuevo.getPassword()));
        params.add(new BasicNameValuePair("email", nuevo.getEmail()));

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(getQuery(params));

        ...

        private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
        {
            StringBuilder result = new StringBuilder();
            boolean first = true;

            for (NameValuePair pair : params)
            {
                if (first)
                    first = false;
                else
                    result.append("&");

                result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
                result.append("=");
                result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
            }

            return result.toString();
        }
    
answered by 16.12.2017 в 22:54