I am new to Socket Programming.
I have connected to Server from my Client Program,But the response im getting is
Header info + Actual content(what i need ie XML data)
I just want to remove Headers.
This is my Code :
public class TestSocket{
public static void main(String args[]){
try{
URL url = new URL("http://xxxx.de:8080/abcd");
String path=url.getFile();
int port = url.getPort();
String host = url.getHost();
Socket cliSocket = new Socket(host,port);
String req = "yyyy";
req="name="+req;
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(cliSocket.getOutputStream()));
bw.write("POST " + path + " HTTP/1.0\r\n");
bw.write("Host: " + host + "\r\n");
bw.write("Content-Length: " + req.length() + "\r\n");
bw.write("Content-Type: application/x-www-form-urlencoded\r\n");
bw.write("\r\n");
bw.write(req);
bw.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(cliSocket.getInputStream()));
String line;
System.out.println("Step 4 : Getting Input Stream");
StringBuffer serverData = new StringBuffer("");
while ((line = rd.readLine()) != null) {
serverData.append(line);
}
System.out.println(serverData);
String data = serverData.toString();
int index = data.indexOf("<");
String xmlData =null;
if(index!=-1){
xmlData = data.substring(index);
System.out.println("XML Content :"+xmlData);
}else{
System.out.println("XML Data Not Retrived");
}
bw.close();
rd.close();
}catch(java.net.UnknownHostException uh){
System.out.println("UH : Host Not Found ");
}catch(IOException ioe){
System.out.println("IO Exp "+ioe.getMessage());
}catch(Exception e){
System.out.println("Exp "+e.getMessage());
}
}
}
Response :
HTTP/1.1 200 OKServer: Apache-Coyote/1.1X-Powered-By: Servlet 2.4; JBoss-4.2.3.GA (build: SVNTag=JBoss_4_2_3_GA date=200807181417)/JBossWeb-2.0Content-Type: text/xml;charset=UTF-8Content-Length: 1110Date: Wed, 30 Apr 2014 12:13:10 GMTConnection: close
And then XML Data ,
I just only need XML data , Not HTTP/1.1 200 OKServer: Apache-Coyote/1.1X-Powered-By: Servlet 2.4; JBoss-4.2.3.GA .......... etc
Use something like HttpClient form Apache HttpComponents. This save you from most the HTTP stuff and lets you deal directly with the message content.
Related
I understand Java but am completely inexperienced with connecting to web applications. How would I take the following HTTP POST request and make it JSON? The overall purpose is to send information from a Java application to an online Ruby on Rails SQLite3 database.
import java.io.*;
import java.net.*;
public class HTTPPostRequestWithSocket {
public void sendRequest() {
try {
String params = URLEncoder.encode("param1", "UTF-8") + "="
+ URLEncoder.encode("value1", "UTF-8");
params += "&" + URLEncoder.encode("param2", "UTF-8") + "="
+ URLEncoder.encode("value2", "UTF-8");
String hostname = "nameofthewebsite.com";
int port = 80;
InetAddress addr = InetAddress.getByName(hostname);
Socket socket = new Socket(addr, port);
String path = "/nameofapp";
// Send headers
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream(), "UTF8"));
wr.write("POST " + path + " HTTP/1.0rn");
wr.write("Content-Length: " + params.length() + "rn");
wr.write("Content-Type: application/x-www-form-urlencodedrn");
wr.write("rn");
// Send parameters
wr.write(params);
wr.flush();
// Get response
BufferedReader rd = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
wr.close();
rd.close();
socket.close(); // Should this be closed at this point?
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am trying to create a simple socket based server/client communication between a Java-based socket server and PHP-based socket client. I am getting all the responses as expected but not immediately. Here is what I am trying to do. PHP client sends a command to the Java server, it responds back with an answer. This answer should be displayed on PHP page immediately. Then a second command is sent and again, the server sends a response which should be displayed immediately. However in my case, the responses are 'echoed' only after entire socket based communication is terminated. That is after I close the socket connection from PHP client.
Following is my Java Socket Server code:
public class MultiThreadServer implements Runnable {
Socket csocket;
MultiThreadServer(final Socket csocket) {
this.csocket = csocket;
}
private static void download(final String url) {
try {
final URL downloadURL = new URL(url);
URLConnection conn = null;
try {
conn = downloadURL.openConnection();
final InputStream inputStream = conn.getInputStream();
final long filesize = conn.getContentLength();
System.out.println("Size of file : " + (filesize / 1024)
+ " (kb)");
final FileOutputStream outputStream = new FileOutputStream(
System.getProperty("user.dir") + "/test.exe");
final long startTime = System.currentTimeMillis();
final byte[] buffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
final long endTime = System.currentTimeMillis();
System.out.println("File downloaded");
System.out.println("Download time in sec. is : "
+ ((endTime - startTime) / 1000));
outputStream.close();
inputStream.close();
} catch (final IOException e) {
e.printStackTrace();
}
} catch (final MalformedURLException e) {
e.printStackTrace();
}
}
public static void main(final String args[]) throws Exception {
final ServerSocket ssock = new ServerSocket(3333);
System.out.println("Listening on " + ssock.toString());
while (true) {
final Socket sock = ssock.accept();
System.out.println("Connected to " + sock.getRemoteSocketAddress());
new Thread(new MultiThreadServer(sock)).start();
}
}
#Override
public void run() {
try {
final BufferedReader br = new BufferedReader(new InputStreamReader(
this.csocket.getInputStream()));
final BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(this.csocket.getOutputStream()));
bw.write(this.csocket.getRemoteSocketAddress().toString()
.replace("/", "")
+ "\n");
bw.flush();
String line;
while ((line = br.readLine()) != null) {
if (line.equalsIgnoreCase("getMacName")) {
final String macName = InetAddress.getLocalHost()
.getHostName();
bw.write(macName + "\n");
bw.flush();
System.out.println("Machine Name : " + macName);
} else if (line.equalsIgnoreCase("getMacIP")) {
final String macIP = InetAddress.getLocalHost()
.getHostAddress();
bw.write(macIP + "\n");
bw.flush();
System.out.println("Machine IP : " + macIP);
} else if (line.equalsIgnoreCase("getCurrentVersion")) {
final String currVersion = "0.1a";
bw.write(currVersion + "\n");
bw.flush();
System.out.println("Current Version : " + currVersion);
} else if (line
.equalsIgnoreCase("downUrl:http://webserver/webapp/test.exe")) {
final String url = line.substring(8);
bw.write("Downloading : " + url + "\n");
bw.flush();
MultiThreadServer.download(url);
System.out.println("URL : " + url);
} else if (line.equalsIgnoreCase("exit")) {
bw.write("Closing\n");
bw.flush();
bw.close();
br.close();
System.out.println("Exiting!");
this.csocket.close();
break;
}
}
} catch (final IOException e) {
e.printStackTrace();
}
}
}
Following is my sample PHP client source code:
<html>
<head>
<title>Socket Connection Test</title>
</head>
<body>
<h3>Testing Socket Connection</h3>
<br>
<?php
$host="127.0.0.1";
$port = 3333;
$fp;
$macName;
$macIP;
$message;
$result;
// open a client connection
$fp = fsockopen ($host, $port, $errno, $errstr);
if (!$fp)
{
$result = "Error: Could not open socket connection! Error No: " . $errno . ". Error String: " . $errstr;
die($result);
}
else
{
$message = fgets ($fp, 1024);
$message = trim($message);
echo "Connected to remote server on current port : " . $message;
echo "<br>";
sleep(5);
// get machine name
fwrite ($fp, "getMacName\n");
$macName = fgets ($fp, 1024);
$macName = trim($macName);
echo "Machine Name : " . $macName;
echo "<br>";
sleep(5);
// get IP address
fwrite ($fp, "getMacIP\n");
$macIP = fgets ($fp, 1024);
$macIP = trim($macIP);
echo "Machine IP : " . $macIP;
echo "<br>";
sleep(5);
fwrite ($fp, "getCurrentVersion\n");
$currVersion = fgets ($fp, 1024);
$currVersion = trim($currVersion);
echo "Current Version : " . $currVersion;
echo "<br>";
sleep(5);
fwrite ($fp, "downUrl:http://webserver/webapp/text.exe\n");
$downResponse = fgets ($fp, 1024);
$downResponse = trim($downResponse);
echo "Download Response : " . $downResponse;
echo "<br>";
sleep(5);
fwrite ($fp, "exit\n");
$exitStatus = fgets ($fp, 1024);
fclose ($fp);
echo "Connection Closed.";
}
?>
</body>
</html>
In this case, the entire PHP output is displayed at the end. I even tried putting sleeps at various places, however it seems to be waiting for socket connection to be closed before writing the output. How can I can I get the output "LIVE". Like a normal chat communication? What am I doing wrong here?
Your script works okay, and has no big flaws for what you're looking for. Since you obtain the desired result when you run the script from command line rather than a web browser, we can pinpoint the cause of the issue: the HTTP protocol
HTTP isn't made for sustained connections (like you're used to with Java sockets) but it's simplified workflow is based along the lines of Request/Elaborate/Response/Forget. Therefore, you can't have a "live chat" with a pure HTML/PHP over HTTP solution.
Alas, not all your hopes are lost! To implement a "live" communication you can use Ajax, which isn't too hard to get used to. I've said "live" because it's still an HTTP based solution, but at least you can have requests and receive responses from within the same webpage, which is the closest you can get with the HTML/PHP/AJAX triad.
It seems you dont understand php with http well .
You will get the HTML response only after your php client code completes execution. (i.e) all your echo's will be put in place where you specified and returned as a whole.
Putting sleep will only delay the execution.
I am writing a web client. I have the following code.
public class Connection extends Thread{
public final static int PORT = 1337;
private ServerSocket svrSocket = null;
private Socket con = null;
public Connection(){
try{
svrSocket = new ServerSocket(PORT);
System.out.println("Conected to: " + PORT);
}catch(IOException ex)
{
System.err.println(ex);
System.out.println("Unable to attach to port");
}
}
public void run(){
while(true)
{
try{
con = svrSocket.accept();//on this part the program stops
System.out.println("Client request accepted");
PrintWriter out = new PrintWriter(con.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
out.println("GET /<index.html> HTTP/1.1");
out.println("***CLOSE***");
System.out.println(in.readLine());
/*
String s;
while((s = in.readLine()) != null)
{
System.out.println(s);
}*/
out.flush();
out.close();
in.close();
con.close();
System.out.println("all closed");
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}
}
The run method will be used latter on. That I have is a file called index.html. This file is in the same file as the java code. What I am trying to do with the request is send the HTML file. But if I run this program on a web browser localhost:1337 the following gets displayed.
GET /<index.html> HTTP/1.1
***CLOSE***
This should not get displayed. The page that results of the HTML code in the index.html should get displayed.
Index.html code:
<html>
<head>
<title> </title>
</head>
<body bgcolor = "#ffffcc" text = "#000000">
<h1>Hello</h1>
<p>This is a simple web page</p>
</body>
</html>
How do I get this html page to display in the browser?
Thank you
t seems that all is good on your code, it seems you need to read the HTTP header from the input stream so you can get the requested file name and then use the Socket output stream to write the response from the file.
OutputStream output = con.getOutputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String fileName = readHeader(in);
String baseDir = System.getProperty("my.base.dir", "/home/myname/httpserver");
boolean exist = true;
InputStream fileIn = null;
try {
File requestedFile = new File(baseDir, fileName);
fileIn = new FileInputStream(requestedFile);
} catch(Exception e){
exist = false;
}
String server = "Java Http Server";
String statusLine = null;
String typeLine = null;
String body = null;
String lengthLine = "error";
if (exist) {
statusLine = "HTTP/1.0 200 OK" + "\r\n";
//get content type by extension
typeLine = "Content-type: html/text \r\n";
lengthLine = "Content-Length: " + (new Integer(fileIn.available())).toString() + "\r\n";
} else {
statusLine = "HTTP/1.0 404 Not Found" + CRLF;
typeLine = "text/html";
body = "<HTML>" + "<HEAD><TITLE>404</TITLE></HEAD>" + "<BODY>404 Not Found"+"</BODY></HTML>";
}
output.write(statusLine.getBytes());
output.write(server.getBytes());
output.write(typeLine.getBytes());
output.write(lengthLine.getBytes());
output.write("\r\n".getBytes());
if (exist) {
byte[] buffer = new byte[1024];
int bytes = 0;
while ((bytes = fileIn.read(buffer)) != -1) {
output.write(buffer, 0, bytes);
}
} else {
output.write(body.getBytes());
}
//close sreams
You are confusing a couple of things. First of all: what you are writing is a server, not a client.
Second: You are not following the HTT Protocol.
The line GET /<index.html> HTTP/1.1 (which is wrong, it should be GET /index.html HTTP/1.1) is a request that is sent by the client (like a web browser). Instead, it is your server sending this.
A quick solution:
Instead of sending this static text (the line with the GET and the one with the ***CLOSE***), read the content of your index.html file and print it to your out stream.
EDIT: Here's a quick overview of the http data flow:
The client (e.g. a browser) connects to the server
The client sends it's request, something like
GET /theFileIWant.html HTTP/1.1\r\n
Host: localhost\r\n
\r\n
at this point, the client usually stops sending anything and waits for the server to respond. That is called the "request/response" model.
The server reads the request data and finds out what it has to do.
The output (in this case: a file's content) is sent to the client, preceded by HTTP response headers.
The connection can be kept open or closed, depending on the HTTP headers of both client's request and server's response.
I have a java servlet class that is performing a GET to a specific URL. I am also passing data as part of the GET.
What I need, is in my HTTP Server code that recieves this data, how do I insert user based response data into the Header back so my calling Java servlet class can read it.
I can read standard response things like .getResponseCode() etc, but I need to insert my own response into the header some how. How can this be done? and how can I read it?
This is my java servlet send class:
public void sendRequest(String data, String sendUrl) throws Throwable{
String messageEncoded = URLEncoder.encode(data, "UTF-8");
String message = URLDecoder.decode(messageEncoded);
System.out.println("messageEncoded : " + messageEncoded);
System.out.println("messageDecoded : " + message);
try {
URL url = new URL(sendUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("GET");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(message);
writer.close();
BufferedReader rd = null;
StringBuilder sb = null;
String line = null;
System.out.println(" *** headers ***");
for (Entry<String, List<String>> headernew : connection.getHeaderFields().entrySet()) {
System.out.println(headernew.getKey() + "=" + headernew.getValue());
}
System.out.println(" \n\n*** Body ***");
rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line + '\n');
}
System.out.println("body=" + sb.toString());
System.out.println("connection.getResponseCode() : " + connection.getResponseCode());
System.out.println("connection.getResponseMessage()" + connection.getResponseMessage());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// Ok
} else {
// Server returned HTTP error code.
}
} catch (MalformedURLException e) {
// ...
System.out.println(this.getClass() + " : MalformedURLException Error occured due to: " + e);
} catch (IOException e) {
System.out.println(this.getClass() + " : IOException Error occured due to: " + e);
}
}
I am trying to send an HTML POST request over telnet in Java, I have some XML content which I have to send. But when I try to achieve in java, i am getting "Connection Reset" error. But the same when I do it over putty(unix), I am getting the response xml correctly.
Java Program I used : (Resulting in Connection Reset error)
public class Telnet {public static void main(String[] args) throws Exception {
Socket socket = new Socket("hostname", 10020);
String xmled = "<?xml version=1.0?><methodCall><methodName>GetVoucherDetails</methodName><params><param><value><struct><member><name>serialNumber</name><value><string>1038291567</string></value></member><member><name>networkOperatorId</name><value><string>vno2</string></value></member></struct></value></param></params></methodCall>";
System.out.println("Params: " + xmled);
try {
Writer out = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
out.write("POST /someContext HTTP/1.1\r\n");
out.write("Accept: text/xml\r\n");
out.write("Connection: close\r\n");
out.write("Content-Length: 489\r\n");
out.write("Content-Type: text/xml\r\n");
out.write("Host: ws2258:10010\r\n");
out.write("User-Agent: ADM/2.4/6.2\r\n");
out.write("Authorization: Basic cHBtc3VzZXI6dnNfJF9wcG11NWVy\r\n");
out.write(xmled);
out.write("\r\n");
out.flush();
InputStream inputstream = socket.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
String string = null;
string = bufferedreader.readLine();
System.out.println(string);
while ((string = bufferedreader.readLine()) != null) {
System.out.println("Received " + string);
}
} catch(Exception e) {
e.printStackTrace();
} finally {
socket.close();
}
}
}
Please suggest me something, I am new to socket programming.
In your Socket constructor, did you mean to put port 10020? HTTP implies port 80 unless your web server is listening on port 10020.
I finally have found the solution for this problem. The fix was quiet simple at the end. We had to send the entire XML content in one single line rather then putting into multiple lines.