Java Connection Reset - java

We are using SOAP 1.1
and we have also created a WCF Webservice which is working fine in SOAP UI
when we tried to get a response via SOAP in java, the connection was established but no data was received.
We got this response :
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Encoding: gzip
Vary: Accept-Encoding
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Tue, 16 Oct 2012 12:05:28 GMT
Content-Length: 148
After this no SOAP response was received and this error was thrown:
ERROR : java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:189)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:154)
at java.io.BufferedReader.readLine(BufferedReader.java:317)
at java.io.BufferedReader.readLine(BufferedReader.java:382)
at ICNumber.main(ICNumber.java:113)
here is the code snippet:
String SOAPRequest ="<soapenv:Envelope"+
"xmlns:soapenv"+
"=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">"+
"<soapenv:Header>"+
"</soapenv:Header>"+
"<soapenv:Body>"+
"<tem:ICNumberValidation>"+
"<tem:ICNumber>"+
strIC+
"</tem:ICNumber>"+
"</tem:ICNumberValidation>"+
"</soapenv:Body>"+
"</soapenv:Envelope>";
try {
//Create socket
String hostname = "192.168.1.xx";
int port = 90;
InetAddress addr = InetAddress.getByName(hostname);
SocketAddress sockaddr = null;
try
{
sockaddr = new InetSocketAddress(addr, (port));
}
catch(IllegalArgumentException e)
{
System.out.println("ErrorCode-6001");
}
Socket sock = new Socket();
try
{
sock.connect(sockaddr, 10000);
}
catch(Exception e)
{
System.out.println( "ErrorCode-6001");
}
//Send header
String path = "/Service1.svc";
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(),"UTF-8"));
// You can use "UTF8" for compatibility with the Microsoft virtual machine.
wr.write("POST " + path + " HTTP/1.1\r\n");
wr.write("Accept-Encoding: gzip,deflate\r\n");
wr.write("Host: " + hostname + "\r\n");
wr.write("Content-Length: " + SOAPRequest.length() + "\r\n");
wr.write("Content-Type: text/xml; charset=\"utf-8\"\r\n");
wr.write("SOAPAction: \"http://tempuri.org/IService1/ICNumberValidation\"\r\n");
wr.write("Connection: Keep-Alive\r\n");
wr.write("User-Agent: Apache-HttpClient/4.1.1 (java 1.5)\r\n");
wr.write("\r\n");
//Send data
wr.write(SOAPRequest);
wr.flush();
//response read
BufferedReader reader = new BufferedReader( new InputStreamReader( sock.getInputStream() ) );
String line = "";
String line2 = "";
while((line = reader.readLine()) != null)
{
line2 = line2 + line+"\n";
System.out.println(line2);
}
System.out.println(line2);

Related

Why InputStreamReader cannot read the content of a websocket package?

To understand the behaviour of the websocket, I created a simple SocketServer in java to exchange the messages. The server is expected to follow the operations as:
1) Listening at port 8080
2) A websocket handshake message generated manually on the browser client and received by the server.
3) Construct a response to the handshake message and reply to the client
4) Read out actually websocket info bytes with the same connection.
The problem has happened at step 4. when the server has responded with the handshake message, the InputStreamReader can no longer receive any new message. It blocked at the readline() method even though the client has sent the message already. From wireshark, I can see the client sent message and server respond ack. Any help would be appreciated, thanks.
Update: I just noted this question has been asked before. I will study the suggestions on the other posts first.
Update: The behavior is as same as this post:
Weird websocket behavior: only send data when close the tab
When the webtab closes, the read stream received the data package.
wireshark screen captures:
The tcp stream trace
The packages sequence
The log:
inputline: GET / HTTP/1.1
inputline: Host: localhost:8080
inputline: Connection: Upgrade
inputline: Pragma: no-cache
inputline: Cache-Control: no-cache
inputline: Upgrade: websocket
inputline: Origin: file://
inputline: Sec-WebSocket-Version: 13
inputline: User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
inputline: Accept-Encoding: gzip, deflate, br
inputline: Accept-Language: en,zh-TW;q=0.8,zh;q=0.6,zh-CN;q=0.4
inputline: Sec-WebSocket-Key: Yin4xn04vr9iBH1b2dU15A==
inputline: Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
inputline:
response: HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: +Y9whLTzCdyN1INpAxjkO6yD2Nw=
The server socket code:
public class EchoServer {
public static String HTTP_VERSION_HEADER = "HTTP/1.1";
public static void main(String[] args) throws IOException {
int portNumber = 8080;
try (
ServerSocket serverSocket =
new ServerSocket(Integer.parseInt("8080"));
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine;
StringBuilder sb = new StringBuilder();
while ( true) {
inputLine = in.readLine();
if(inputLine == null) {
System.out.println("input is null");
continue;
}
System.out.println("inputline: " + inputLine);
sb.append(inputLine).append(System.lineSeparator());
if(inputLine.equals("")) {
Message msg = new Message(sb.toString(), new Date());
HttpMessage tmpMessage = new HttpMessage(msg.getText(), new Date());
String response = generateHandshakeResponse(tmpMessage);
System.out.println("response: " + response);
out.println(response);
out.flush();
}
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
private static String generateHandshakeResponse(HttpMessage message) {
String webSocketKey = message.getVal(HttpMessage.SEC_WEBSOCKET_KEY);
String webSocketAccept = webSocketKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
byte[] bytes = DigestUtils.sha1(webSocketAccept);
String secWebSocketAcceptVal = Base64.encodeBase64String(bytes);
StringBuilder sb = new StringBuilder();
sb.append(HTTP_VERSION_HEADER).append(" 101 ").append("Switching Protocols\r\n");
sb.append("Upgrade: websocket\r\n");
sb.append("Connection: Upgrade\r\n");
sb.append("Sec-WebSocket-Accept: ").append(secWebSocketAcceptVal).append("\r\n");
sb.append("\n\n") //<--- this line fixed the problem
//log.debug(sb.toString());
return sb.toString();
}
}
The client code:
<!doctype html>
<html lang="en">
<head>
<title>Websocket Client</title>
</head>
<body>
<script>
var exampleSocket = new WebSocket("ws://localhost:8080");
exampleSocket.onopen = function (event) {
console.log("connection opened..");
exampleSocket.send("Can you hear me?");
};
exampleSocket.onmessage = function (event) {
console.log(event.data);
}
function sendMsg(){
console.log("send message..");
exampleSocket.send("hello hello");
}
</script>
<button onclick="sendMsg()" title="send">send</button>
</body>
</html>
Thanks a lot to EJP, the problem is a missing blank line at the response handshake to indicate the end of the message.

Senig an HTTP request doesn't get me to the "service" function in my servlet

I am trying to do a simple servlet connection socket,
I am able to see this webpage and able to get to my servlet(on another eclipse instance) breakpoint when using a web browser.
but when i try to perform the following function:
public void Connect() {
try {
String params = URLEncoder.encode("ID", "UTF-8")
+ "=" + URLEncoder.encode("test", "UTF-8");
params += "&" + URLEncoder.encode("GOAL", "UTF-8")
+ "=" + URLEncoder.encode("Security", "UTF-8");
URL url = new URL(_address);
String host = url.getHost();
int port = url.getPort();
String path = url.getPath();
Socket socket = new Socket(host, port);
// Send headers
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
wr.write("GET " + path + " HTTP/1.0\r\n");
wr.write("Content-Length: " + params.length() + "\r\n");
wr.write("Content-Type: application/x-www-form-urlencoded\r\n");
wr.write("\r\n");
// Send parameters
wr.write(params);
wr.flush();
// Get response
BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
String answer = "";
while ((line = rd.readLine()) != null) {
answer += line;
}
wr.close();
rd.close();
if (answer.indexOf(resourceStrings.ACCESS_GRANTED) != -1)
{
_result = true;
}
}
catch (Exception e) {
_result = false;
}
}
I just recieve the following answer:
HTTP/1.1 302 Found
Server: Apache-Coyote/1.1
Location: http://localhost:8180/Admin/
Date: Mon, 18 Apr 2016 15:00:28 GMT
Connection: close
without getting to my servlet code's breakpoint or retrieve any data from my "service" function in the servlet.
I am using Tomcat 7 if it makes any difference, do you have any idea what is causing this issue?
The parameters of a GET request are sent by appending them to the URL, not in the body of the request.

How to send data via GET method in Socket Programming to Http server in java

I am new to Socket Programming , I have written a program to send get request via HttpURLConnection (it is working fine),
Output I got :
Some XML Data (ie Valid Data)
Now i want to implement same in Socket Programming.
String ul = "http://www.xxxxxxxx.com/cgi-bin/yyyy.cgi?name=abcd&age=25&phone=01454575";
URL url = new URL(ul);
Socket cliSocket = new Socket();
cliSocket.connect(new InetSocketAddress(url.getHost(), 80), 6000);
bw = new BufferedWriter(new OutputStreamWriter(cliSocket.getOutputStream()));
bw.write("GET " + url.getPath() + " HTTP/1.0\r\n");
bw.write("Host: " + url.getHost() + "\r\n");
bw.write("Pragma: cache\r\n");
bw.write("Cache-Control: private, must-revalidate\r\n");
bw.write("Content-Type: application/x-www-form-urlencoded\r\n");
bw.write("\r\n");
bw.flush();
rd = new BufferedReader(new InputStreamReader(cliSocket.getInputStream()));
serverData = new StringBuffer("");
lineSep = System.getProperty("line.separator");
while ((line = rd.readLine()) != null) {
serverData.append(line);
serverData.append(lineSep);
}
data = serverData.toString();
Output I am getting is
HTTP/1.1 200 OK
Server: nginx
Date: Wed, 28 May 2014 09:55:25 GMT
Content-Type: text/html
Connection: close
{Error: 1}

400 Bad request when pass xml to webservice

I'm new in webservice.
I've to pass xml to aspx web service called plog.asmx
here is my code
String xmldata = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<SOAP:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" >" +
"<![CD[<soap:Body>" +
"<SubmitJob xmlns=\"http://www.xdel.biz/XWS/\"> " +
"<APIKey>"+ API_KEY +"</APIKey>" +
"<Job>" +
"<Customer_Name>"+ Customer_Name +"</Customer_Name>" +
"<Address1>"+ Address1 +"</Address1>" +
"<Address2>"+ Address2 +"</Address2>" +
"<Postal_Code>"+ Postal_Code +"</Postal_Code>" +
"<Phone_Number>"+ Phone_Number +"</Phone_Number>" +
"<Mobile_Number>"+ Mobile_Number +"</Mobile_Number>" +
"<Order_Reference>"+ Order_Reference +"</Order_Reference>" +
"<Delivery_Instructions>"+ Delivery_Instructions +"</Delivery_Instructions>" +
"</Job>]]>" +
"</SubmitJob>" +
"</soap:Body>]]>" +
"</SOAP:Envelope>";
System.out.println(xmldata);
try{
//Create socket
String hostname = "www.xdel.biz";
int port = 80;
InetAddress addr = InetAddress.getByName(hostname);
Socket sock = new Socket(addr, port);
System.out.println(sock.toString());
//Send header
String path = "/xws/plog.asmx";
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(),"UTF-8"));
// You can use "UTF8" for compatibility with the Microsoft virtual machine.
wr.write("POST " + path + " HTTP/1.1\r\n");
wr.write("Host: www.xdel.biz\r\n");
wr.write("Content-Type: text/xml; charset=utf-8\r\n");
wr.write("Content-Length: " + xmldata.length() + "\r\n");
wr.write("SOAPAction: \"http://www.xdel.biz/XWS/SubmitJob\" \r\n");
wr.write("\r\n");
//Send data
wr.write(xmldata);
wr.flush();
System.out.println("1");
// Response
BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String line;
while((line = rd.readLine()) != null){
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
when I run the code, I got error like this
HTTP/1.1 400 Bad Request
Cache-Control: private
Content-Type: text/xml; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 13 Dec 2012 09:37:12 GMT
Content-Length: 0
I googled the error and tried to fix but no solution come out..
A good ideia would be to use an API that implements SOAP webservice and is already tested.
I used this
JAX-WS
400 Bad Request sometimes happens when you mismatch the protocol(SOAP or HTTP)
It could be <![CD[<soap:Body></soap:Body>]]> try to use without ![CD[ ]] block
I already had "Bad Request" consuming a webservice. The thing is, after almost a day looking for an answer, we found out that was the size of the XML consumed, the size of the SOAP Message consumed. The problem is, the application that provides the Webservice to be consumed, must be set up to receive a large XML Data, we had to config our application server to expand to encrease the size of our buffer used to receive the SOAP Message from the client.
That was our expirence. I hope could helps a little.
I had same issue with HttpURLConnection. Adding the below two properties resolved my 400 Bad Request issue:
httpConn.setRequestProperty("Content-Type","text/xml; charset=utf-8");
httpConn.setRequestProperty("soapAction", soapAction);
Note: this error usually appears when you try to read response.

How do i forward the HTTP request back to the browser? Proxy Java

final int portNumber = 8128;
String str;
int start = 0;
int endSg = 0;
int endCom = 0;
String ReqWeb=null;
System.out.println("Creating server socket on port " + portNumber);
ServerSocket serverSocket = new ServerSocket(portNumber);
BufferedReader inFromServer;
OutputStream out;
PrintWriter outw;
Socket forwardSocket = null;
while (true)
{
Socket socket = serverSocket.accept(); //get client request
String from = socket.getInetAddress().toString();
System.out.println("Accepted connection from " + from);
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
pw.println("What's your request?");
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//System.out.println(str);
while((str = br.readLine())!=null){
System.out.println(str);
if(str!=null){
start = str.indexOf("Host: ") + 6;
endSg = str.indexOf(".sg", start) + 3;
endCom = str.indexOf(".com", start) + 4;
if(((endSg>3)||(endCom>4))&&(start>4)){
if(endSg>3)
ReqWeb = str.substring(start, endSg);
else if(endCom>3)
ReqWeb = str.substring(start, endCom);
}
}
}
System.out.println(ReqWeb);
if(ReqWeb!=null){
//ReqWeb = str.substring(start);
System.out.println(ReqWeb);
forwardSocket = new Socket(ReqWeb, 80);
}
pw.println(str);
pw.println(ReqWeb);
//socket.close();
if(forwardSocket!=null){
inFromServer = new BufferedReader(new InputStreamReader(forwardSocket.getInputStream()));
out = forwardSocket.getOutputStream();
outw = new PrintWriter(out, false);
outw.print(str);
}
}
Output :
Creating server socket on port 8128
Accepted connection from /127.0.0.1
null
Accepted connection from /127.0.0.1
GET (http://)stackoverflow.com/questions/12900825/how-do-i-forward-the-http-request-back-to-the-browser-proxy-java HTTP/1.0
Host: stackoverflow.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Proxy-Connection: close
Pragma: no-cache
now this is the output i got, should i store in a byte array to send it back to the server to request for the page? I am still having trouble forwarding this request ):
You'll need to open another socket to the intended target (as per firefox's request) and send the request there. Keep the socket that's connected to firefox open because when you get the response from the intended target, you'll read it from the target and write it back to firefox. Depending on your pipelining settings in firefox, the connection either may then close or may make more requests.

Categories

Resources