user4109372
user4109372

Reputation: 11

Parsing a RESTful PUT

How do I access the HTTP PUT message (JSON format) in a Java server application? The HTTP PUT is sent from a Python client.

Python Client so far:

    import http.client 
    import urllib

    values = {'s':'basic','submit':'search'}
    data = urllib.parse.urlencode(values)


    headers = headers['Content-length']=str(len(bytes(data, 'utf-8')))
    connection =  http.client.HTTPConnection('localhost',8080)
    connection.request("PUT", "/file", body=data.encode("utf-8"))

When PUT gets to the Java server - how do I get the message (data from Python)?

So far, this is what I have in Java:

import java.io.*;
import java.net.*;

class JavaServer {

    public static void main(String args[]) throws Exception {

        String fromclient;

        ServerSocket Server = new ServerSocket (8080);

        System.out.println("TCPServer Waiting for client on port 8080");

        Socket connected = Server.accept();
        System.out.println( " THE CLIENT"+" "+ connected.getInetAddress() +":"+connected.getPort()+" IS CONNECTED ");

        BufferedReader inFromClient = new BufferedReader(new InputStreamReader (connected.getInputStream()));

        fromclient = inFromClient.readLine();
        System.out.println( "RECIEVED:" + fromclient );

    }
}

Upvotes: 1

Views: 115

Answers (2)

user4109372
user4109372

Reputation: 11

Thank you. That did work. I also just found this:

StringBuilder buffer = new StringBuilder();
String line;
while ((line = inFromClient.readLine()) != null) {
buffer.append(line);
}

System.out.println("buffer.toString = " + buffer.toString());

Which also works, however, the json message seems to have a lot of extra characters and seems to be mixed up. I am new at working with JSON. Maybe that is normal or I need double quotes around it. I am actually sending times and ip addresses and values. Do numbers require special formatting with JSON?

Upvotes: 0

Fish Biscuit
Fish Biscuit

Reputation: 133

You will need to iterate over your "inFromClient"

So something like:

    while((fromclient = inFromClient.readLine()) != null){
        System.out.println( "RECIEVED:" + fromclient );
    }
    inFromClient.close();

Upvotes: 2

Related Questions