I need to retrieve Json
values for a given URL using HTTP POST
, but I'm having trouble getting started.
How can I perform such an operation on Android?
I need to retrieve Json
values for a given URL using HTTP POST
, but I'm having trouble getting started.
How can I perform such an operation on Android?
On Android we can use some libraries to not support this task like the Volley or Okhttp .
I'll show you an example with Okhttp:
Let's add the libraries in build.gradle :
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.squareup.okhttp:okhttp:2.6.0'
compile 'com.google.code.gson:gson:2.3' // Tranforma Json para Objeto
}
In order to make a request, we have to separate it from Thread
principal, so it does not interfere with the graphical interface:
private final class Send extends AsyncTask<Void, Void, Void>
{
final Context mContext;
Send(final Context mContext)
{
this.mContext = mContext;
}
@Override
protected Void doInBackground(Void... params) {
final OkHttpClient mClient = new OkHttpClient();
RequestBody body = null;
Request.Builder requestBuilder = new Request.Builder();
requestBuilder.url("www.url.com.br/send");
final HashMap<String, String> mParams = new HashMap<>(0);
mParams.put("param1", "Valo1" );
mParams.put("param4", "Valor2" );
mParams.put("param3", "Valor3" );
final JSONObject jsonObject = new JSONObject(mParams);
body = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString());
requestBuilder.post(body);
OkHttpModel.loadHeaders(requestBuilder, mContext);
try{
final Response response = mClient.newCall(requestBuilder.build()).execute();
final String txtResult = response.body().string();
MeuObjeto meuObjeto = new Gson().fromJson(txtResult, MeuObjeto.class);
}catch (final IOException e){ }
return null;
}
}
The MeuObjeto
must contain the same Json parameters returned by the request, and the same name:
class MeuObjeto{
private String valor_1;
private Integer valor_2;
private Boolean status;
// Get's and Set's
}
If the names are different, we can map with Annotation:
class MeuObjeto{
@SerializedName("valor_1")
private String valor1;
@SerializedName("valor_2")
private Integer valor2;
@SerializedName("status")
private Boolean valor3;
// Get's and Set's
}
Any questions, we are available!