This question already has answers here:
java.io.IOException: unexpected end of stream on Connection in android
(12 answers)
Closed 3 years ago.
Calling one of our in-house web services seems to be giving the following error:
java.io.IOException: unexpected end of stream on Connection{webservicessandbox.xxx.com:443, proxy=DIRECT# hostAddress=174.143.185.13 cipherSuite=TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA protocol=http/1.1} (recycle count=0)
From what I've seen elsewhere, this is being pointed to as a server issue, but we're not seeing this problem when the WS is being called in browser or in IOS. I've used both OkHTTP and a manual HTTPUrlConnection implementation and it hasn't seemed to make any difference. Does anyone have any ideas?
OKHttp:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.addHeader("Authorization", "Bearer " + apiToken)
.addHeader("content-type", "application/json")
.url(uri)
.build();
HTTPURLConnection:
URL myURL = new URL(uri);
HttpsURLConnection myConnection = (HttpsURLConnection) myURL.openConnection();
myConnection.setConnectTimeout(TIMEOUT_MILLISEC);
myConnection.setDoOutput(false);
myConnection.setRequestMethod("GET");
myConnection.setRequestProperty("Authorization", "Bearer " + apiToken);
myConnection.setRequestProperty("content-type", "application/json");
int respCode = myConnection.getResponseCode();
Please try the potential solutions (in my opinion) below:
1- Try to use retryOnConnectionFailure(true) as below:
OkHttpClient client = new OkHttpClient.Builder()
.retryOnConnectionFailure(true)
.build();
2- Try to add: request.addHeader("Connection","close") (most cases this is the solution, respecting to Kartik's answer.)
Request request = new Request.Builder()
.addHeader("Authorization", "Bearer " + apiToken)
.addHeader("content-type", "application/json")
.addHeader("Connection","close")
.url(uri)
.build();
3- Please increase the response time of the server (set it as high as possible) and try again.
Also see: OkHTTP Websocket: Unexpected end of steam on Connection
Both the client and server needs to close the connection once they are finished.
In your OkHttp request builder, add this line: .header("Connection", "close").
Also check the network tab of your browser inspector to see which headers the browser is sending. Match those headers in your code and it should work.
This error TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 is related to server. A possible reason could be, the server is shut down.
Related
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 !
I have Java 11.0.1 installed in MacOs Mojave and I started a local
Vertx http server which listens on http://0.0.0.0:8085/home (Just
return "hello world").
However, if I send request to 0.0.0.0:8085/home programmatically by
using java, it takes 5 seconds to reach local server. But if I
send to localhost:8085/home, it will immediately reach server and
receive response.
Besides, I tried Chrome, cURL and Python to send http request to both
0.0.0.0:8085/home and localhost:8085/home, both of them will immediately receive response. So is this a Java 11 bug or not?
String url = "http://0.0.0.0:8085/home" // Or http://localhost:8085/home;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
System.out.println(con.getResponseCode()); // 5 seconds to receive
If I use Java 11 Http Client new feature, it will hang forever.
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://localhost:8085/home")).build();
HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
I'm trying to integrate a payment service 'Mollie' (http://www.mollie.nl) which works over HTTPS requests into a Java environment.
As for this posts i'll be using following request to explain:
Within PHP (since I have a PHP background) I can work with cURL:
$ curl -X GET https://api.mollie.nl/v1/methods \
-H "Authorization: Bearer API-KEY"
Which has a response:
Testing the REQUEST from DHC (or Postman) return correct response.
So within Java i'm using the Jersey library to try to access the Request:
Client client = Client.create();
WebResource webResource = client.resource("https://api.mollie.nl/v1/methods");
webResource.header("Authorization", "Bearer API-KEY");
ClientResponse response = webResource
.header("Content-Type", "application/json;charset=UTF-8")
.type("application/json")
.accept("application/json")
.get(ClientResponse.class);
int statusCode = response.getStatus();
if (statusCode == 401) {
throw new AuthenticationException("Invalid Username or Password");
}
String responseCall = response.getEntity(String.class);
When executing the Java code the request throws a ClientHandlerException:
HTTP Status 500 - com.sun.jersey.api.client.ClientHandlerException: java.net.ConnectException: Connection timed out: connect
I'm running the Java test from a Apache localhost server.
But I can't figure out why the Java request gives a timeout since the authentication header seems to be set correct (at least to me).
What I did notice is when visiting the path of the request https://api.mollie.nl/v1/methods it shows a pop-up for authentication.
It would be nice to get some usefull tips or information about this issue.
Am I missing something?
Thanks!
Given all is is working correctly (I'm not sure why it would cause a timeout), one thing I see wrong is your usage of
webResource.header("Authorization", "Bearer API-KEY");
header returns an WebResource.Builder, and does not add the header to the current WebResource. So the request you are sending doesn't have the header. You can check it by adding a LoggingFilter
client.addFilter(new com.sun.jersey.api.client.filter.LoggingFilter(System.out));
You can fix this by doing
ClientResponse response = webResource
.header("Authorization", "Bearer API-KEY");
.header("Content-Type", "application/json;charset=UTF-8")
Just moving the header to the method chaining.
I have resolved above issue. Apparently the work PROXY server was blocking outgoing HTTPS requests. Testing from a non-proxy environment fixed the issue. Thanks for all advice!
How one is supposed to tell OkHttp that a connection to an HTTP server should be closed after a request has finished?
Suppose I use the following code to make a request to google.com
OkHttpClient cl = new OkHttpClient();
Request req = new Request.Builder()
.url("http://www.google.com")
.header("Connection", "close")
.get()
.build();
Response res = cl.newCall(req).execute();
System.out.println("Response message: " + res.message());
System.out.println("Reponse body: " + res.body().string());
by using "Connection: close" I'm able to get the remote server to send a FIN (if I don't, the remote server just hangs awaiting for new requests). Still, on the client side no FIN is produced, and the connection stays half opened apparently for an indefinitive amount of time.
Ugh, it's a regression in OkHttp 2.0.0-RC1. Fix is out for review.
I'm trying to connect and post to a simple java webservice, running the post's URL from chrome succeeded, but android code skip the following lines (without throwing errors), but the webservice doesn't accept the post
HttpPost post = new HttpPost(setFacebookEventsAddress+userId+"/"+accesstoken);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
HttpResponse response = client.execute(post);
the webservice method signature handling the above request:
#GET
#Path("setData/{user_id}/{accessToken}")
#Produces(MediaType.APPLICATION_JSON+ ";charset=utf-8")
public String setData(#PathParam("user_id") String user_id,
#PathParam("accessToken") String accessToken) {
since I manage to post throw my browser, anyone can help with what's wrong with my android code?
URL url = new URL(setFacebookEventsAddress+userId+"/"+accesstoken);
HttpURLConnection con = (HttpURLConnection) url
.openConnection();
ja = readStream(con.getInputStream());
Using HttpURLConnection instead of HttpPost did the trick for me, thanks for all the helpers!
It is not possible to say with any certainty (given the evidence), but my guess would be that the expression
setFacebookEventsAddress + userId + "/" + accesstoken
is evaluating to a different URL to the one you are using from the web browser.
I suggest that you try the following:
Turn on request logging on your server, and compare the URLs in the requests being sent.
Modify your client to print out the response status code and the response body. The latter is likely to be an error page that will give you more clues.
Another possible problem is that your code doesn't appear to be sending any body with the POST request.
On revisiting this, the problem was that you were using / trying to do a POST to a web service that you had configured to support GET only. I expect that if you had looked at the status code you would have found that the response code was "Method not supported".