Program stuck in socketRead0 method when requesting with OkHttp - java

I developed a Java library for Twitter API here using OkHttp3 4.8.1.
Unfortunately, it looks like after having sent a request, once everything is finished, the program never stops and is stuck in SocketInputStream.
When not using cache, it is stuck in waitForReferencePendingList method of Reference class instead :
I tried everything, closing connection explicitly in my code like this, updating the version of OkHttp, but still the same. Any idea ?
If needed, here is the full code where the request is done, in summary :
Request request = new Request.Builder()
.url(url)
.get()
.headers(Headers.of("Authorization", "Bearer " + bearerToken))
.build();
OkHttpClient client = new OkHttpClient.Builder().build()
Response response = client.newCall(request).execute();
String stringResponse = response.body().string();
return Optional.ofNullable(TwitterClient.OBJECT_MAPPER.readValue(stringResponse, classType));

Finally adding client.connectionPool().evictAll(); elsewhere (in my post request to get a bearer token) solved the problem !

Related

Getting a {"status":100,"errormsg":"Failed to parse text in form param"} when making api call

I'm trying to make an api call using the below code
'''
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
//this is where the error is beign thrown
RequestBody body = RequestBody.create(mediaType, "text="+this.body);
Request request = new Request.Builder()
.url("https://text-sentiment.p.rapidapi.com/analyze")
.post(body)
.addHeader("content-type", "application/x-www-form-urlencoded")
.addHeader("x-rapidapi-key", "API Key")
.addHeader("x-rapidapi-host", "Host")
.build();
client.newCall(request).enqueue(new Callback() {
'''
But when I run it I get "{"status":100,"errormsg":"Failed to parse text in form param"} "
This only happens when I try to make a call with a bigger string, when smaller strings are applied I get the results i need to have.
Interesting! I'm expecting you're using Text Sentiment Analysis Method API on RapidAPI Hub. It is working fine for me even for the large strings as well. Generally 100 status code indicate clients to avoid sending large amounts of data over the network when the server, based on the request headers, intends to reject the request.
It should be working now. You can check again. You can send your query to support team of RapidAPI if, in case, it is still not working for you.

SparkJava GET Handler Returning NULL After Serialization of Long

I'm trying to write a simple server with SparkJava but I am having considerable difficulty serialize a long using Gson and transmitting the JSON to an OkHttp client program inside a GET handler. The server returns NULL, more specifically response.body.string() is
<html><body><h2>404 Not found</h2></body></html>
Any ideas on what the issue could be? thanks.
Here is the GET handler:
get("routingEngine/getDefaultRoute/distance", (request,response) ->{
response.type("application/json");
long distance = 100;
return gson.toJson(distance);
});
Here is the client code making the simple request (please disregard the parameters (requestParameters) being passed in along with the request, they just provide information to an irrelevant before filter):
// build url
HttpUrl url = new HttpUrl.Builder()
.scheme("http")
.host("127.0.0.1")
.port(4567)
.addPathSegment("routingEngine")
.addPathSegment("getDefaultRoute")
.addPathSegment("distance")
.build();
// build request
Request getDefaultRouteDistanceRequest = new Request.Builder()
.url(url)
.post(RequestBody.create(JSON,gson.toJson(requestParameters)))
.build();
// send request
Call getDefaultRouteDistanceCall = httpClient.newCall(getDefaultRouteDistanceRequest);
Response getDefaultRouteDistanceResponse = getDefaultRouteDistanceCall.execute();
// parse response
// testing
System.out.println(getDefaultRouteDistanceResponse.body().string());
The last line leads to the following output
<html><body><h2>404 Not found</h2></body></html>
The endpoint you created was a GET endpoint and the call being made is for POST.

How to send x-www-form request on java?

Above is what im trying to send
In java this is what I have
RequestBody formBody = new FormBody.Builder()
.add("param1", "abc")
.add("param2", "abc")
.add("param3", "abc")
.build();
Request request = new Request.Builder()
.url("http://localhost:3001/addsomething")
.post(formBody)
.build();
doesn't seem to work. I have OkHttpClient but I'm not sure how to use it to send the above result
What are you confused about? I'm a little unsure. I did a little research but it seems the only thing you're missing is a client, and then sending the request you've created and receive a response back.
To create a client, look at the most updated documentation on OkHttpClient, but this is what I found:
OkHttpClient client = new OkHttpClient();
And then send your request using that client using:
Response response = client.newCall(request).execute();
Then you can proceed to do something with that response.
All you have to understand is that you're creating a request (essentially asking the server for some information). Depending on your request, you'll get a response back (as in above), which you can then use to get whatever you're looking for.

Java - RestTemplate 405 Method Not Allowed Although Postman Call Works

I am experiencing a weird issue when working with RestTemplate. I'm using a certain REST API and there I want to update something using PUT.
Thus, in e.g. Postman I am sending this request:
PUT http://fake/foobar/c/123 with a certain body
This update via Postman is successful. If I now execute the same call in Java via a RestTemplate, I am getting a 405 Method Not Allowed:
HttpHeaders headers = createHeader();
HttpEntity<Offer> httpEntity = new HttpEntity<>(bodyEntity, headers);
String url = "http://fake/foobar/c/123"; //Created dynamically, but here pasted for sake of simplicity
RestTemplate restTemplate = new RestTemplate(...);
ResponseEntity<OfferResponse> response = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, OfferResponse.class);
...
I compared the URL again and again. If I copy the URL logged in the console and copy it to Postman, I can do the update successfully. I also compared the headers and everything. Everything is equal to how it is done via Postman.
Is there any potential other reason for such a behavior (another reason than I am too stupid comparing the headers etc. and missing something)? Other PUT, POST calls etc. against this API are working fine, otherwise I would have assumed that there is a general problem with my usage of RestTemplate
Code 405 Method Not Allowed means the HTTP verb (GET, POST, PUT, etc.) you use against this end-point is known but not accepted by the API.
If you can't post the details of your API as #Dinesh Singh Shekhawat suggested, I will first try to use Postman Code feature and get an automatically generated code for Java (OkHTTP or UniRest) of the request. You can find this option on the right part below the Send button. Copy this code and try to perform the request.
Then compare this request with yours.
You can always use HttpPut instead of RestTemplate if it's not a requirement:
HttpClient client = HttpClientBuilder.create().build();
String url = "http://fake/foobar/c/123";
HttpHeaders headers = createHeader();
HttpEntity<Offer> httpEntity = new HttpEntity<>(bodyEntity, headers);
HttpPut httpPut = new HttpPut(url);
httpPut.setEntity(httpEntity);
HttpResponse response = client.execute(httpPut);
I was facing the same problem. Later I printed the request and URL in the logs.
I found that I was using a wrong endpoint.
Can you please try to print the URL and the request in the logs and check if those are expected and correct?
Just in case it helps someone else: I was encountering the same issue and for me it was just the issue of a trailing slash / on the URL. In insomnia (similar to postman) I had a trailing slash, in code I didn't. When I added the slash to my code everything worked.
failure: http://localhost:8080/api/files
success: http://localhost:8080/api/files/
Of course it could also be the other way around, so just double check the actual api definition.

Request working fine in postman, but getting a 403 in OkHTTP

I'm trying to make a request to the Genius API, but I'm running into some issues using OkHTTP. This is my small script I'm using to make the call:
public class OkHttpScript {
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.header("Authorization", "Bearer uDtfeAgTKL3_YnOxco4NV6B-WVZAIGyuzgH6Yp07FiV9K9ZRFOAa3r3YoxHVG1Gg")
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
public static void main(String[] args) throws IOException {
OkHttpScript okHttpScript = new OkHttpScript();
String response = okHttpScript.run("http://api.genius.com/songs/378195/");
System.out.println(response);
}
}
When I run this script, I get a 403 error:
{"meta":{"status":401,"message":"This call requires an access_token. Please see: https://genius.com/developers"}}
For reference, here is a picture of me making the same exact request with Postman, and it works:
Any ideas on what the problem could be?
Edit:
Not sure if this is normal, but when I print out my request object that gets built, I see no indication that there are headers in the request:
Request{method=GET, url=http://api.genius.com/songs/378195/, tag=null}
Is what I get. Could this be part of the problem?
Edit2:
Nevermind, doing a
System.out.println(newRequest.headers());
gives me what I originally put in:
Authorization: Bearer 4mfDBVzCnp2S1Fc0l0K0cfqOrQYjRrb-OHi8W1f-PPU7LNLI6-cXY2E727-1gHYR
So I figured out what my problem was. I'm not sure of the details behind it, but I should have been using my URL has https://api.genius.com/songs/378195/ instead of http://api.genius.com/songs/378195/
Postman seems fine with the http, but OkHttp needed https.
Not sure how your server side is written, I had the same problem today when requesting someone else's service. My solution was to change the User-Agent, even if PostmanRuntime/7.26.10
You should add an interceptor for okhttp something like this should work
How to handle auth0 403 error without adding specific code everywhere (Retrofit/okhttp/RxAndroid)
*Used Alex Hermstad Answer
--> Use https instead of http in android ,
Postman seems fine with the http, but OkHttp needed https.
I was stuck for a day for this error 403 forbidden in android , but giving 200 success in Postman .

Categories