4

I am working on a REST Client experimenting with the tinkerpop database using using HttpURLConnection.

I am trying to send over a 'GET - CONNECT'. Now I understand (from some net research) that if I use doOutput(true) the 'client' will a 'POST' even if I setRequestMethod 'GET' as POST is the default (well ok?) however when I comment out the the doOutput(true) I get this error:

java.net.ProtocolException: cannot write to a URLConnection if doOutput=false - call setDoOutput(true)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:995)
at RestContent.handleGetConnect(RestContent.java:88)

at RestClient.main(RestClient.java:42)`

Here is the communication code snip I have tried various option with setUseDoOutPut().

//connection.setDoInput(true);
connection.setUseCaches (false);
connection.setDoOutput(true);
connection.setAllowUserInteraction(false);

// set GET method 
try {
    connection.setRequestMethod("GET");
} catch (ProtocolException e1) {
    e1.printStackTrace();
    connection.disconnect();
}

Exception at connection.setRequestMethod("GET") in the other case. Any hints?

4

1 回答 1

1

以下代码工作正常: URL 是一个支持 GET 操作的 Rest URL。

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    //connection.setDoOutput(true);
    InputStream content = (InputStream) connection.getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(content));
    String line;
    while ((line = in.readLine()) != null) {
        System.out.println(line);
    }
于 2013-09-26T09:40:33.163 回答