1
I need to recover values Json
of a given URL using HTTP POST
, but I’m having a hard time getting started.
How can I perform such operation on Android?
1
I need to recover values Json
of a given URL using HTTP POST
, but I’m having a hard time getting started.
How can I perform such operation on Android?
1
On Android we can use some libraries to assist in this task as the Volley or Okhttp.
I will show 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
}
To carry out a requisition, we have to separate it from the Thread
main, so that 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!
Browser other questions tagged android
You are not signed in. Login or sign up in order to post.
Hello! You want to do it with Java Httppost, or you can use some library for it?
– Thiago Luiz Domacoski
I have a feeling he won’t be able to answer your question either.
– durtto