Android: Send data via POST

Asked

Viewed 2,499 times

2

I know how to do this in other programming languages, however, when searching for examples of how to send data using POST in the Android, I just find examples that use discontinued classes, like:

  • HttpClient
  • HttpPost
  • HttpResponse
  • HttpEntity
  • EntityUtils
  • NameValuePair
  • BasicNameValuePair

I’m looking for a way to send a json via POST of an app Android and retrieve them in an application with Servlets. The part of the Servlets is not a problem. I can recover a json and treat it using lib Gson google.

2 answers

1

Use the retrofit, read on: here

Example of use:

Create an interface:

 public interface SUAINTERFACE {
     @POST("users/new")
     Call<User> createUser(@Body User user);//dados passados no corpo
    }

Method for request:

    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.github.com/") //sua base_url
        .addConverterFactory(GsonConverterFactory.create())
        .build();

    SUAINTERFACE service = retrofit.create(SUAINTERFACE.class);
    Call<User> user = service.createUser(new User());
    call.enqueue(new Callback<User>() {
    @Override
    public void onResponse(Response<User> response, Retrofit retrofit) {
        Log.i("retorno",response.message().equals("OK") //sucesso 200
        //dados da resposta:
        response.body();
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
});

More about the retrofit you can find: here

1


Uses native Android library Volley. Here has another example of how to implement.

final String url = "some/url";
final JSONObject jsonBody = new JSONObject("{\"type\":\"example\"}");

new JsonObjectRequest(url, jsonBody, new Response.Listener<JSONObject>() { ... });
Here is the source code and JavaDoc (@param jsonRequest):

/** 
 * Creates a new request. 
 * @param method the HTTP method to use 
 * @param url URL to fetch the JSON from 
 * @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and 
 *   indicates no parameters will be posted along with request. 
 * @param listener Listener to receive the JSON response 
 * @param errorListener Error listener, or null to ignore errors. 
 */ 
public JsonObjectRequest(int method, String url, JSONObject jsonRequest,
        Listener<JSONObject> listener, ErrorListener errorListener) {
    super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
                errorListener);
} 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.