HttpUrlConnection getOutputStream() throwing java.net.SocketException: Unexpected end of file from server - java

I am trying to invoke a REST webservice using java code.
I am able to execute it thru Rest Client Postman.
My code:
URL url = new URL(appURL);
httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestMethod("POST");
httpCon.setDoInput(true);
httpCon.setUseCaches(false);
httpCon.setAllowUserInteraction(false);
httpCon.setDoOutput(true);
httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpCon.setRequestProperty("Host", "www.astecanalytics.com");
httpCon.setRequestProperty("Expect", "100-continue");
OutputStream outstream = httpCon.getOutputStream();
I am getting below error:
java.net.SocketException: Unexpected end of file from server
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:772)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:633)
at sun.net.www.protocol.http.HttpURLConnection.doTunneling(HttpURLConnection.java:1789)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:183)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1091)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250)
at com.ktt.business.keywords.webservice.ExecuteWebServiceKeyword.postHTTPRequestAndGetRespone(ExecuteWebServiceKeyword.java:618)
Can someone help?

Since the response from server is ok, then no issues on the server side.
Compare the request body send through Rest Client with the one send from code.
Then try to map.
Check this tutorial link:http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/
This helped me when I tried to do the same thing as you are currently trying

Related

Failing to send JSON data using POST-method and HTTPS to Webserver with Java

Currently I'm trying to address a webserver using HTTPS and POST method and send a JSON file to this server. I have already tried several tutorials but unfortunately I can only find examples for HTTP and Post and not HTTPS. Did I forget to implement something?
I would like to provide the code of the server, but I only received the address and the format of the JSON files.
Has anyone had the problem before or can help me?
Thank you
public static void main(String[] args) throws IOException {
URL url = new URL(" https://webservice.com:1234");
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
//con.setDoInput(true);
con.setDoOutput(true);
String jsonInputString = "\"ID\": \"12\"";
System.out.println(jsonInputString);
try(OutputStream os = con.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
os.flush();
}
System.out.println(con.getResponseCode());
Unfortunately I always get this error message:
Exception in thread "main" javax.net.ssl.SSLException: Unsupported or
unrecognized SSL message at
java.base/sun.security.ssl.SSLSocketInputRecord.handleUnknownRecord(SSLSocketInputRecord.java:439)
at
java.base/sun.security.ssl.SSLSocketInputRecord.decode(SSLSocketInputRecord.java:184)
at
java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:108)
at
java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1180)
at
java.base/sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1091)
at
java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:402)
at
java.base/sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:567)
at
java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:187)
at
java.base/sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1362)
at
java.base/sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1337)
at
java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:247)
at test.main(test.java:40)
Process finished with exit code 1
Sometimes the https returns SSL errors if the service is not secure. This happens a lot in localhost or some servers with only http. Maybe try removing the 's'
Many thanks for all your help, in a discussion with the developer of the web service I was able realize that the server does not support HTTPS. That means the link to the server was wrong - http//: instead of https//:
So with the HttpURLConnection con = (HttpURLConnection)url.openConnection(); it works just fine.

PORT Change in error case: HttpURLConnection

I am consuming API using HttpURLConnection in my android application and its running fine but if I get response code except then 200 ok (like 404, 500) my port is changing when I hit next request after error response code:
my code for android request is below and wireshark log as well:
try {
url = new URL(path_url + apiMsg); //in the real code, there is an ip and a port
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept","*/*");
}
Please refer wireshark log:
https://files.fm/u/w7umrwwk
So how to avoid PORT change in error scenario as well like in success 200 case, so that we continue to run on the same PORT.
read about sun.net.http.errorstream.enableBuffering in HttpURLConnection source code.
By default when response code is >= 400 then the connection is closed.
It is a clean though not so efficient way of handling error streams.
Instead of setting obscure system properties to handle this, it would be better to move to a proper http client like apache.

send http request from IIS to GCM using java

I am trying to send Json message from my [java application server] to [GCM]:
the java server app located on IIS server (Windows server 2008 R2).
here is my function:
public static String post(String apiKey, String json){
try{
URL url = new URL("https://android.googleapis.com/gcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type:", "application/json");
conn.setRequestProperty("Authorization:", "key="+apiKey); // apiKey is valid browser apiKey.
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeUTF(json);
wr.flush();
wr.close();
/*I've deleted the respond check from the question*/
}
but I fail to send!, and does not get any message or exception.
I think that the server itself doesnt let me send http requests!
is this true? how to solve?
I recommend using the Sender and Message objects instead. The sample GCM server code uses those. Sample server code can be seen here.
If you really insist on handling the connection yourself, you can look at the underlying HttpURLConnection implementation of the Sender object here.
It does appear that there are certain differences between the Sender code and your request properties. Hope this helps.

IHS (Apache) 400 Error when adding UUID header to HttpUrlConnection

I need to add a header ("correlationIdHeader") to a GET Request using Java's HttpUrlConnection. However the server (IBM Http Server - built on Apache) answers with a 400 Error and the following info:
Request header field is missing ':' separator
My code:
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty("correlationIdHeader", UUID.randomUUID().toString());
conn.setRequestMethod(HttpMethod.GET.name());
conn.setRequestProperty("Accept", contentType);
int responseCode= conn.getResponseCode();
Any idea what could be happening here?
EDIT: it has to do with UUID.randomUUID().toString(). I don't know why but it doesn't like UUID's format. Why?

Getting error 502/504 when trying to get InputStream

URL queryUrl = new URL(url);
InputStream inputStream = null;
HttpsURLConnection connection = (HttpsURLConnection) queryUrl.openConnection();
connection.setRequestProperty("User-Agent", "My Client");
connection.setRequestMethod("GET");
connection.setDoInput(true);
inputStream = connection.getInputStream();
Hi,
I'm using the above code to perform an HttpGet query.
I'm getting once in a few tries an exception that server returned error code 502 or 504 (both scenarios occur).
The exception is thrown in the line :
inputStream = connection.getInputStream()
Any ideas?
Your help would be appreciated.
Thanks in advance
The error code in 5xx indicates some issue with Server or proxy. Rfc Statement
Response status codes beginning with the digit "5" indicate cases in which the server is
aware that it has erred or is incapable of performing the request. Except when responding
to a HEAD request, the server SHOULD include an entity containing an explanation of the
error situation, and whether it is a temporary or permanent condition. User agents SHOULD
display any included entity to the user. These response codes are applicable to any request method.
Please check what is the actual error by reading the error steam of url connection as below:
If the HTTP response code is 4nn (Client Error) or 5nn (Server Error), then you may want to read the HttpURLConnection#getErrorStream() to see if the server has sent any useful error information.
InputStream error = ((HttpURLConnection) connection).getErrorStream();
Also I think for working with http requests, you can use Apache HttpClient instead of directly working with HttpUrlConnection. Using HttpClient is lot more easier.

Categories

Resources