For reasons of library compatibility issues I would like to use HttpURLConnection to call requests on an API.
Here is the code I use with OkHttp to get a token access:
private void getAccessToken(){
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody requestBody = new FormEncodingBuilder().add("grant_type", "authorization_code")
.add("client_id", "1568xxxxxxxxxxxxxxxxxjro.apps.googleusercontent.com")
.add("client_secret", "AMe0xxxxxxxxxxxx")
.add("redirect_uri", "")
.add("code", serverCode)
.build();
Request request = new Request.Builder()
.url("https://www.googleapis.com/oauth2/v4/token")
.post(requestBody)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
Log.i("severcode","failure");
}
#Override
public void onResponse(Response response) throws IOException {
try {
JSONObject jsonObject = new JSONObject(response.body().string());
token = jsonObject.optString("access_token");
tokenExpired = SystemClock.elapsedRealtime() + jsonObject.optLong("expires_in") * 1000;
Log.i("severcode",String.valueOf(token));
createGooglePhotosClient();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
So I would like to know how to get the equivalent of requestbody to pass it in setRequestProperty ()?
Thanks for your help
The request body is not a request property (header), it's the body of the request, and without OkHttp or other supporting libraries you have to format it yourself, encode any special characters that need to be encoded etc.
String requestBody = "grant_type=authorization_code&client_id=1568xxxxxxxxxxxxxxxxxjro.apps.googleusercontent.com&"
+ "client_secret=AMe0xxxxxxxxxxxx&redirect_uri=&code=" + serverCode + "\n\n";
byte[] requestBodyBytes = requestBody.getBytes("UTF-8");
Once you have the request body, you write it to the connection's output stream. For example:
connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
connection.setDoOutput(true);
out = connection.getOutputStream();
out.write(requestBodyBytes)
out.flush();
Related
I have searched everywhere but I couldn't find my answer, is there a way to make a simple HTTP request? I want to request a PHP page / script on one of my websites but I don't want to show the webpage.
If possible I even want to do it in the background (in a BroadcastReceiver)
UPDATE
This is a very old answer. I definitely won't recommend Apache's client anymore. Instead use either:
Retrofit
OkHttp
Volley
HttpUrlConnection
Original Answer
First of all, request a permission to access network, add following to your manifest:
<uses-permission android:name="android.permission.INTERNET" />
Then the easiest way is to use Apache http client bundled with Android:
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(URL));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
String responseString = out.toString();
out.close();
//..more logic
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
If you want it to run on separate thread I'd recommend extending AsyncTask:
class RequestTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
}
}
You then can make a request by:
new RequestTask().execute("http://stackoverflow.com");
unless you have an explicit reason to choose the Apache HttpClient, you should prefer java.net.URLConnection. you can find plenty of examples of how to use it on the web.
we've also improved the Android documentation since your original post: http://developer.android.com/reference/java/net/HttpURLConnection.html
and we've talked about the trade-offs on the official blog: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
Note: The Apache HTTP Client bundled with Android is now deprecated in favor of HttpURLConnection. Please see the Android Developers Blog for more details.
Add <uses-permission android:name="android.permission.INTERNET" /> to your manifest.
You would then retrieve a web page like so:
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
}
finally {
urlConnection.disconnect();
}
I also suggest running it on a separate thread:
class RequestTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... uri) {
String responseString = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if(conn.getResponseCode() == HttpsURLConnection.HTTP_OK){
// Do normal input or output stream reading
}
else {
response = "FAILED"; // See documentation for more info on response handling
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
}
}
See the documentation for more information on response handling and POST requests.
The most simple way is using the Android lib called Volley
Volley offers the following benefits:
Automatic scheduling of network requests. Multiple concurrent network
connections. Transparent disk and memory response caching with
standard HTTP cache coherence. Support for request prioritization.
Cancellation request API. You can cancel a single request, or you can
set blocks or scopes of requests to cancel. Ease of customization, for
example, for retry and backoff. Strong ordering that makes it easy to
correctly populate your UI with data fetched asynchronously from the
network. Debugging and tracing tools.
You can send a http/https request as simple as this:
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.yourapi.com";
JsonObjectRequest request = new JsonObjectRequest(url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (null != response) {
try {
//handle your response
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(request);
In this case, you needn't consider "running in the background" or "using cache" yourself as all of these has already been done by Volley.
Use Volley as suggested above. Add following into build.gradle (Module: app)
implementation 'com.android.volley:volley:1.1.1'
Add following into AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
And add following to you Activity code:
public void httpCall(String url) {
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// enjoy your response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// enjoy your error status
}
});
queue.add(stringRequest);
}
It replaces http client and it is very simple.
private String getToServer(String service) throws IOException {
HttpGet httpget = new HttpGet(service);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
return new DefaultHttpClient().execute(httpget, responseHandler);
}
Regards
With a thread:
private class LoadingThread extends Thread {
Handler handler;
LoadingThread(Handler h) {
handler = h;
}
#Override
public void run() {
Message m = handler.obtainMessage();
try {
BufferedReader in =
new BufferedReader(new InputStreamReader(url.openStream()));
String page = "";
String inLine;
while ((inLine = in.readLine()) != null) {
page += inLine;
}
in.close();
Bundle b = new Bundle();
b.putString("result", page);
m.setData(b);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
handler.sendMessage(m);
}
}
As none of the answers described a way to perform requests with OkHttp, which is very popular http client nowadays for Android and Java in general, I am going to provide a simple example:
//get an instance of the client
OkHttpClient client = new OkHttpClient();
//add parameters
HttpUrl.Builder urlBuilder = HttpUrl.parse("https://www.example.com").newBuilder();
urlBuilder.addQueryParameter("query", "stack-overflow");
String url = urlBuilder.build().toString();
//build the request
Request request = new Request.Builder().url(url).build();
//execute
Response response = client.newCall(request).execute();
The clear advantage of this library is that it abstracts us from some low level details, providing more friendly and secure ways to interact with them. The syntax is also simplified and permits to write nice code.
I made this for a webservice to requerst on URL, using a Gson lib:
Client:
public EstabelecimentoList getListaEstabelecimentoPorPromocao(){
EstabelecimentoList estabelecimentoList = new EstabelecimentoList();
try{
URL url = new URL("http://" + Conexao.getSERVIDOR()+ "/cardapio.online/rest/recursos/busca_estabelecimento_promocao_android");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
if (con.getResponseCode() != 200) {
throw new RuntimeException("HTTP error code : "+ con.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));
estabelecimentoList = new Gson().fromJson(br, EstabelecimentoList.class);
con.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return estabelecimentoList;
}
Look at this awesome new library which is available via gradle :)
build.gradle: compile 'com.apptakk.http_request:http-request:0.1.2'
Usage:
new HttpRequestTask(
new HttpRequest("http://httpbin.org/post", HttpRequest.POST, "{ \"some\": \"data\" }"),
new HttpRequest.Handler() {
#Override
public void response(HttpResponse response) {
if (response.code == 200) {
Log.d(this.getClass().toString(), "Request successful!");
} else {
Log.e(this.getClass().toString(), "Request unsuccessful: " + response);
}
}
}).execute();
https://github.com/erf/http-request
This is the new code for HTTP Get/POST request in android. HTTPClient is depricated and may not be available as it was in my case.
Firstly add the two dependencies in build.gradle:
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
Then write this code in ASyncTask in doBackground method.
URL url = new URL("http://localhost:8080/web/get?key=value");
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
int statusCode = urlConnection.getResponseCode();
if (statusCode == 200) {
InputStream it = new BufferedInputStream(urlConnection.getInputStream());
InputStreamReader read = new InputStreamReader(it);
BufferedReader buff = new BufferedReader(read);
StringBuilder dta = new StringBuilder();
String chunks ;
while((chunks = buff.readLine()) != null)
{
dta.append(chunks);
}
}
else
{
//Handle else
}
For me, the easiest way is using library called Retrofit2
We just need to create an Interface that contain our request method, parameters, and also we can make custom header for each request :
public interface MyService {
#GET("users/{user}/repos")
Call<List<Repo>> listRepos(#Path("user") String user);
#GET("user")
Call<UserDetails> getUserDetails(#Header("Authorization") String credentials);
#POST("users/new")
Call<User> createUser(#Body User user);
#FormUrlEncoded
#POST("user/edit")
Call<User> updateUser(#Field("first_name") String first,
#Field("last_name") String last);
#Multipart
#PUT("user/photo")
Call<User> updateUser(#Part("photo") RequestBody photo,
#Part("description") RequestBody description);
#Headers({
"Accept: application/vnd.github.v3.full+json",
"User-Agent: Retrofit-Sample-App"
})
#GET("users/{username}")
Call<User> getUser(#Path("username") String username);
}
And the best is, we can do it asynchronously easily using enqueue method
I'm using an asynchronous request (because synchronous doesn't work correctly with this API), the OkHttp3 library. Inside the request, I get a response in the form of JSON. I need to somehow pass values from Json to a class variable. I decided to try it this way, but it doesn't work.
public String sessionId = null;
...
public QRcodeReader() throws Exception {
this.sessionId = null;
}
... // between this code I have 1 function, which reg my number.
// in this func I need to confirm my phone by code in SMS.
public void SmsCode(String Code) // String get from another class
{
SmsJson smsJson = new SmsJson("*phoneNumber*", "*secret_key*", "*os*", Code);
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
RequestBody body = RequestBody.create(
MediaType.parse("application/json"), gson.toJson(smsJson));
Request request = new Request.Builder()
.url("https://irkkt-mobile.nalog.ru:8888/v2/auth/phone/verify")
.addHeader("Host", HOST)
.addHeader("Accept", ACCEPT)
.addHeader("Device-OS", DEVICE_OS)
.addHeader("Device-ID", DEVICE_ID)
.addHeader("clientVersion", CLIENT_VERSION)
.addHeader("Accept-Language", ACCEPT_LANGUAGE)
.addHeader("User-Agent", USER_AGENT)
.post(body)
.build();
httpClient.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(#NonNull Call call, #NonNull Response response) throws IOException {
try (Response responseBody = httpClient.newCall(request).execute()) {
if (!responseBody.isSuccessful())
throw new IOException("Unexpected code " + responseBody);
// Here I try to transfer data from request to class variable. Not Work.
SetSessionId(Objects.requireNonNull(responseBody.body()).string());
System.out.println(Objects.requireNonNull(responseBody.body()).string());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
});
}
void SetSessionId(String sessionId){
this.sessionId = sessionId;
}
I need to use SessionID further along here:
public String GetTicketID(String QR){
TicketID ticketID = new TicketID(QR);
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
RequestBody body = RequestBody.create(
MediaType.parse("application/json"), gson.toJson(ticketID));
Request request = new Request.Builder()
.url("https://irkkt-mobile.nalog.ru:8888/v2/ticket")
.addHeader("Host", HOST)
.addHeader("Accept", ACCEPT)
.addHeader("Device-OS", DEVICE_OS)
.addHeader("Device-ID", DEVICE_ID)
.addHeader("clientVersion", CLIENT_VERSION)
.addHeader("Accept-Language", ACCEPT_LANGUAGE)
.addHeader("User-Agent", USER_AGENT)
.addHeader("sessionId", sessionId) // Here I get NULL and exception!
.post(body)
.build();
httpClient.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) throws IOException {
try (Response responseBody = httpClient.newCall(request).execute()) {
if (!responseBody.isSuccessful())
throw new IOException("Unexpected code " + responseBody);
System.out.println(Objects.requireNonNull(responseBody.body()).string());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
});
return ""; // Here I need to transfer id to another variable, not did it yet.
}
The problem is that SessionID = Null and the request does not work.
I think I'm doing something wrong, but I can't figure out what. May be it is because async request..
currently working on an Android App and I'm supposed to send JSON data to a server and receive back a response, but the server doesn't recognize the data frame as a JSON type it still shows its content but replies with a 404 code
here's the code I used :
private final OkHttpClient client = new OkHttpClient();
JSONObject jsonObj = new JSONObject();
try{
jsonObj.put("imei",number);
jsonObj.put("longitude", number);
jsonObj.put("latitude", number);
jsonObj.put("speed", number);
jsonObj.put("battery", number);
jsonObj.put("date", date);
jsonObj.put("error", number);
jsonObj.put("acceleroVal", number);
jsonObj.put("apn", string);
} catch (JSONException e) {
e.printStackTrace();
}
String json = jsonObj.toString();
RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
RequestBody formBody = new FormBody.Builder()
.build();
Request request = new Request.Builder()
.url("http://xxxx.com:2000/api/xxx")
.put(formBody)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NonNull Call call, #NonNull IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(#NonNull Call call, #NonNull Response response) throws IOException {
if(response.isSuccessful()) {
ResponseBody responseBody = response.body();
}
any help is appreciated, feel free to adjust the code.
I'm using retrofit. To catch response i'm using Interceptor:
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.interceptors().add(myinterceptor);
here is code of interceptor:
new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
if (path.equals("/user")){
String stringJson = response.body().string();
JSONObject jsonObject = new JSONObject(stringJson);
jsonObject.put("key",1);
//here I need to set this new json to response and then return this response
How to change body in OkHttp Response?
Add this
MediaType contentType = response.body().contentType();
ResponseBody body = ResponseBody.create(contentType, jsonObject);
return response.newBuilder().body(body).build();
after your response modification. jsonObject is the modified JSON you want to return.
Below is Response Intercepter class where you can intercept okkhttp responce and add your own response. and send it to retrofit.
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.ResponseBody;
import retrofit2.Response;
public class ApiResponseInterceptor implements Interceptor {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
okhttp3.Response response = chain.proceed(request);
if(response.code() == 200) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("code",200);
jsonObject.put("status","OK");
jsonObject.put("message","Successful");
MediaType contentType = response.body().contentType();
ResponseBody body = ResponseBody.create(contentType, jsonObject.toString());
return response.newBuilder().body(body).build();
} catch (JSONException e) {
e.printStackTrace();
}
} else if(response.code() == 403) {
}
return response;
}
}
Yow will get your modified response here in your retrofit callback
call.enqueue(new Callback<EventResponce>() {
#Override
public void onResponse(Call<EventResponce> call, Response<EventResponce> response) {
// you will get your own modified responce here
}
#Override
public void onFailure(Call<EventResponce> call, Throwable t) {
}
});
As a minor change I wouldn't use the string() method cause it can be called only once on this request. You do use the response.newBuilder() so other interceptors down the chain will be able to call string() on your new one but I found myself wasting a couple of hours because I was actually calling it twice :P.
So i suggest something like the following
BufferedSource source = response.body().source();
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.buffer();
String responseBodyString = buffer.clone().readString(Charset.forName("UTF-8"));
Here's a tight, complete example of adding an interceptor that modifies JSON to an OkHttpClient. It uses GSON to manage the JSON.
client.addInterceptor(chain -> {
final Request request = chain.request();
final String path = request.url().uri().getPath();
final Response response = chain.proceed(request);
String body = response.body().string();
final JsonElement element = new JsonParser().parse(body);
if ("/the/endpoint/you/want/to/modify".equals(path)){
final JsonObject object = element.getAsJsonObject();
// v v v v v v All this for these lines v v v v v v v
object.addProperty("some_json_name","some_json_value");
object.addProperty("existing_property","updated_value");
object.addProperty("numbers_work_too",1.2);
// ^ ^ ^ ^ ^ ^ All this for these lines ^ ^ ^ ^ ^ ^ ^
body = object.toString();
}
return response.newBuilder().body(ResponseBody.create(response.body().contentType(), body)).build();
});
JSONObject postdata = new JSONObject();
try {
postdata.put("citizenId", "2222222222222");
postdata.put("accuracy", 3043.323);
postdata.put("provider", "wifi");
postdata.put("gpsTime", 1111111111111L);
postdata.put("lat", 23434.564);
postdata.put("lng", 34343.5445);
postdata.put("appId", "201");
} catch(JSONException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
RequestBody body = RequestBody.create(MEDIA_TYPE,postdata.toString());
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
final OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
// final OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
final Request request = new Request.Builder()
.url(base_url)
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJvd25lcklkIjoyLCJvd25lclR5cGUiOiJMRUFERVIiLCJpYXQiOjE1MDE4Mjc4MDMsImV4cCI6MzMwMzc4Mjc4MDMsImF1ZCI6InNlbmRpdC5hc2lhIiwiaXNzIjoic2VsZiJ9.3Gpn3beZfdYsMOLTjksLwmxyfbrfqiojdm1n-gh6CXY")
.addHeader("cache-control", "no-cache")
.build();
client.newCall(request).enqueue(new Callback() {
#SuppressLint("LongLogTag")
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
// response = client.newCall(request).execute();
// Protocol protocol = response.protocol();
// assertEquals(Protocol.HTTP_1_1, protocol);
// BufferedSource source = response.body().source();
// source.request(Long.MAX_VALUE); // Buffer the entire body.
// Buffer buffer = source.buffer();
// String responseBodyString = buffer.clone().readString(Charset.forName("UTF-8"));
if(response.code() == 200) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("code",200);
jsonObject.put("status","OK");
jsonObject.put("message","Successful");
MediaType contentType = response.body().contentType();
ResponseBody body = ResponseBody.create(contentType, jsonObject.toString());
BufferedSource source = response.body().source();
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.buffer();
String responseBodyString = buffer.clone().readString(Charset.forName("UTF-8"));
Log.e("response body responseBodyString ", body.string());
Log.e("response body responseBodyString ", responseBodyString);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("response", String.valueOf(response));
Log.e("response body", String.valueOf(response.body()));
} }catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call call, IOException e) {
Log.e("response onFailure ", String.valueOf(e));
}
});
I am using OKHttp to perform Post request to server, as follow:
public class NetworkManager {
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, JSONObject json) throws IOException {
try {
JSONArray array = json.getJSONArray("d");
RequestBody body = new FormEncodingBuilder()
.add("m", json.getString("m"))
.add("d", array.toString())
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
} catch (JSONException jsone) {
return "ERROR: " + jsone.getMessage();
}
}
}
and call it with:
NetworkManager manager = new NetworkManager();
String response = manager.post("http://www.example.com/api/", jsonObject);
When I try to run the App, it prompts an error in the logcat:
android.os.NetworkOnMainThreadException
at
android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
With reference to other questions in SO, I added this to override the policy:
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Yet I think this is unhealthy and I would like to put the NetworkManager actions to background. How can I do so?
Since OkHttp supports async way too, so IMO you can refer to the following GET request sample, then apply for your POST request:
OkHttpClient client = new OkHttpClient();
// GET request
Request request = new Request.Builder()
.url("http://google.com")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
Log.e(LOG_TAG, e.toString());
}
#Override
public void onResponse(Response response) throws IOException {
Log.w(LOG_TAG, response.body().string());
Log.i(LOG_TAG, response.toString());
}
});
Hope it helps!