0

我正在为一个简单的客户端-服务器程序编写原型。客户端发出一个 HTTP PUT 请求(工作成功),但它没有收到 HTTP 响应并且正在超时。我一直在玩代码并试验 InputStream 和 OutputStream 几个小时,但我错过了一些东西。可能很简单,因为我没有用 Java 做太多的编码。

客户代码:

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());

服务器代码:内部运行方法

BufferedReader fromClient = new BufferedReader(new InputStreamReader(conn.getInputStream()));
if(line.startsWith("PUT")){
                    methodLine = line.split(" ");
                    this.put(fromClient, line, methodLine);
}

put() 方法 - 包含 http 响应

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;
            }
        }
4

1 回答 1

-1

嗯,你可以把这个写在你的回复里,然后我用PostMan测试一下,这告诉我我想看到什么。

HTTP/1.1 200 OK
Content-Type: text/html
COntent-Length: your length
于 2019-08-24T11:01:43.237 回答