Android: Send data via POST

2

I know how to do this in other programming languages, however, when looking for examples of how to send data using POST in Android , I only find examples that use discontinued classes, such as:

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

I'm looking for a way to send json via POST to a Android application and retrieve them in an application with servlets. The servlets part is not a problem. I can retrieve a json and treat it using Google's Gson lib.

    
asked by anonymous 22.03.2016 / 04:45

2 answers

1

Use the 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);
} 
    
22.03.2016 / 14:20
1

Use retrofit, read about: here

Example usage:

Create an interface:

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

Request method:

    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 retrofit you can find: here

    
22.03.2016 / 05:10