I am writing a prototype for a simple client-server program. The client issues an HTTP PUT request (working successfully),but it is not receiving an HTTP response and is timing out. I have been playing around with the code and experimenting with InputStream and OutputStream for hours but I'm missing something. Probably something simple, as I haven't done much coding in Java.
Client Code:
URL url = new URL("http://" + remoteFilepath);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setReadTimeout(5000);
httpCon.setDoOutput(true);
//httpCon.setDoInput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
String tmp = getContent(localFilepath);
System.out.println("tmp: " + tmp);
out.write(tmp + "\n");
out.flush();
httpCon.connect();
System.out.println("before afterClient");
BufferedReader fromClient = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
System.out.println("after fromClient");
String line;
while ((line = fromClient.readLine()) != null) {
System.out.println(line);
}
System.out.println("response code: " + httpCon.getResponseCode() + ", response message: " + httpCon.getResponseMessage());
Server Code: inside run method
BufferedReader fromClient = new BufferedReader(new InputStreamReader(conn.getInputStream()));
if(line.startsWith("PUT")){
methodLine = line.split(" ");
this.put(fromClient, line, methodLine);
}
put() method - contains http response
public void put(BufferedReader fromClient, String line, String[] putLine){
String[] contentLine;
try{
while((line = fromClient.readLine()) != null){
if(line.startsWith("Content-Length:")){
contentLine = line.split(" ");
//get the content, then send back HTTP response
int numChars = Integer.parseInt(contentLine[1]);
char[] cbuf = new char[numChars];
fromClient.readLine(); //skip over blank line
fromClient.read(cbuf); //read the specified number of bytes
System.out.println("cbuf" + new String(cbuf));
//store <file,content> in memory
contentMap.put(putLine[1], new String(cbuf));
//send back HTTP response then break
PrintWriter out = new PrintWriter(
conn.getOutputStream());
out.write("HTTP/1.1 200 OK" + "\n"); //response
out.flush();
break;
}
}