Android HTTP Get to api - java

I´m trying to get data from my api. In postman the request works, here´s the response:
{
"ips_Beacons_BeaconID": 14,
"ips_Beacons_BeaconDescription": "b2",
"ips_Beacons_BeaconLat": 12.3123,
"ips_Beacons_BeaconLon": 32.123,
"ips_Beacons_BeaconImgX": 45,
"ips_Beacons_BeaconImgY": 123
}
I´ve tried and i got the response with Okhttp. However it stopped working for some reason.
Although i got the response, i wish to serialize the json string it and instanciate objects. But i couldn´t get the response out of the onSuccess method inside the callback.
This is what i had that workd but doens´t work anymore:
OkHttpClient client = new OkHttpClient();
String url ="http://192.168.1.95:44374/api/beacons";
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) { e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()){
String myResponse = response.body().string();
listBeacons = objectMapper.readValue(myResponse, new TypeReference<List<Beacon>>(){});
Log.i(TAG, myResponse);
}
}
});
I need the listBeacons List to perform other operations outside this activity.

Related

OKHTTP GET and POST request return empty body message

I want to a upload file on my server and I've decided to try OKHTTP instead of my current method which is based on android own HTTP implementation and AsyncTask.
Anyway, I used OKHTTP and its asynchronous implementation (from its own recipes) but it returns an empty message (the request code is ok, the message is empty) in both GET and POST methods.
Did I implement it wrong or is there anything else remained that I did not considered? In the meantime, I couldn't find a similar case except this which says used AsyncTask.
Here's the code:
Request request;
Response response;
private final OkHttpClient client = new OkHttpClient();
private static final String postman_url = "https://postman-echo.com/get?foo1=bar1&foo2=bar2";
String message_body;
public void Get_Synchronous() throws IOException
{
request = new Request.Builder()
.url(postman_url)
.build();
Call call = client.newCall(request);
response = call.execute();
message_body = response.toString();
//assertThat(response.code(), equalTo(200));
}
public void Get_Asynchronous()
{
request = new Request.Builder()
.url(postman_url)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
public void onResponse(Call call, Response response)
throws IOException
{
message_body = response.toString();
}
public void onFailure(Call call, IOException e)
{
}
});
}
Edit:
I catch the log on response:
onResponse: Response{protocol=h2, code=200, message=, url=https://postman-echo.com/get?foo1=bar1&foo2=bar2}
OK, for anyone who wants to receive an string from a call, response and response.messgage() don't provide that. To catch the response from your provider, you just need to call response.body().string() inside onResponse which returns the message inside your request.
But after all, Retrofit is a better choice if you want to receive a JSON file using
.addConverterFactory(GsonConverterFactory.create(gson)).
If you still want to receive an string just use .addConverterFactory(ScalarsConverterFactory.create()) as explained here.

GET Request returning 403 Forbidden but works on apitester?

I am trying to get the responce from the server but it is returinig 403 forbidden but testing api on apitester.com works.
This is the code how i am reqesting the get method :
public void getResponse(Context context) throws IOException {
OkHttpClient client = new OkHttpClient();
Hmac hmac = new Hmac();
String auth = hmac.txt;
String url = "https://api.hotstar.com/h/v1/play?contentId=1000034502";
Request request = new Request.Builder()
.url(url)
.addHeader("hotstarauth",auth)
.addHeader("referer","https://hotstar.com/movies/2-states/1000034502")
.addHeader("x-country-code","IN")
.addHeader("x-platform-code","TABLET")
.addHeader("x-region-code","undefined")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Toast.makeText(context, "Error Occured", Toast.LENGTH_SHORT).show();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("Server Responded: ", response.toString());
}
});
}
and in response i am getting 403 FORBIDDEN
but using the same config on apitester.com it works !
here is the sharedconig on apitester https://www.apitester.com/shared/checks/dca814bb92fb40af8aecda95cdf2f39c
why i am not getting the response on android ?

Post request with query params and body

I am making use of Retrofit to call the restful webservices in the android, I have come across the scenario like I need to pass query params and request payload object in the retrofit request, so I've tried something like this
#POST("actual url")
Call<ReceiptList> getData(#Query("limit") String limit,
#Query("page") String page,
#Body ReceiptRequestPayload receiptRequestPayload);
Calling API
Call<cutomObject> responseCall = API.getData("10", "1", requestPayload);
responseCall .enqueue(new Callback<cutomObject>() {
#Override
public void onResponse(Call<cutomObject> call, retrofit2.Response<cutomObject> response) {
Log.d(TAG, "onResponse: Receipts"+response);
Log.d(TAG, "onResponse: Receipts"+response.body());
}
#Override
public void onFailure(Call<ReceiptList> call, Throwable t) {
}
});
But it's not working.
Thanks in advance
Use OkHttp Logging Interceptor to log your HTTP request and response data

when does okhttp client cache the server response?

I am using okhttp client 3.5.0 in java to cache the response and server response has below cache-control header:
Cache-Control: private, max-age=0, must-revalidate
First I am trying to make actual network call to get the server response, then in second request I want to get cached response.
Here is my java code:
HttpUrl.Builder httpUrlBuilder = HttpUrl.parse(serverUrl).newBuilder();
HttpUrl httpUrl = httpUrlBuilder.build();
Request request = new Request.Builder()
.url(httpUrl)
.cacheControl(new CacheControl.Builder().maxAge(1, TimeUnit.DAYS).build())
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
System.out.println("***************Response 1**************");
System.out.println("isSucess:"+response.isSuccessful());
Response text = response.cacheResponse();
System.out.println("Cached Response:" + text);
Response networkResponse = response.networkResponse();
System.out.println("Network Response ::" +networkResponse);
}
});
Thread.sleep(5000);
Request request2 = new Request.Builder()
.cacheControl(new CacheControl.Builder().onlyIfCached().build())
.url(httpUrlBuilder.build())
.build();
call = okHttpClient.newCall(request2);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
System.out.println("***********Response 2************");
System.out.println("isSucess:" +response.isSuccessful());
final Response text = response.cacheResponse();
System.out.println("Cached Response:" + text);
Response networkResponse = response.networkResponse();
System.out.println("Network Response:" +networkResponse);
}
});
And below is the second request output:(partial output)
***********Response 2************
isSucess:false
Cached Response:null
Network Response:null
Whether I am missing anything?
OkHttp won’t cache a response unless you read and close the response body. This is what triggers those bytes to be downloaded and saved.
try {
if (response.cacheResponse() == null) {
body.source().skip(Long.MAX_VALUE); // Exhaust response body.
}
} finally {
body.close();
}

Android OkHttp library: GET Request - Exception EOFException: \n not found: size=0 content=

I'm using in my app OkHttp library (http://square.github.io/okhttp/) and in one simple GET request I get this exception:
Caused by: java.io.EOFException: \n not found: size=0 content=...
at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:201)
at com.squareup.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:191)
...
unexpected end of stream on Connection{th.it-bedna.cz:80, proxy=DIRECT# hostAddress=85.118.128.42 cipherSuite=none protocol=http/1.1} (recycle count=0)
Other Get requests to the same address works OK. And if I type this request to the Chrome it works also OK. Do you know where is a problem?
Thanks for any advice.
Edit: code of the GET
public Call doGetRequest(String url, Callback callback) {
com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder()
.url(url)
.build();
Call call = client.newCall(request);
call.enqueue(callback);
return call;
}
Using:
void getData()
{
String url = "http://th.it-bedna.cz/api/v2/event/1/user?i=8";
Singleton.getInstance().doGetRequest(url, new Callback() {
#Override
public void onFailure(Request request, IOException e) {
Log.i("CDT", "onFailure: " + e);
}
#Override
public void onResponse(Response response) throws IOException {
}
});
}
If your server is th.it-bedna.cz as in your logcat info, you can try the following code:
OkHttpClient client = new OkHttpClient();
// GET request
Request request = new Request.Builder()
.url("http://th.it-bedna.cz")
.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());
}
});
I had the same issue with OkHttpClient and HttpURLConnection.
My android emulator was configured to use proxy, but my proxy wasn't accepting connections.
Doesn't mater if you use proxy or not if destination host refuses connection you will get that exception.

Categories