REST HttpURLConnection

5

我正在使用HttpURLConnection尝试对tinkerpop数据库进行REST客户端实验。

我试图发送一个'GET - CONNECT'请求。现在,我了解到(通过一些网络研究),如果我使用doOutput(true),即使我将setRequestMethod设置为'GET','client'也会成为POST,默认情况下是POST(好的?)。但是当我注释掉doOutput(true)时,我会收到以下错误消息:

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)`

这是一段通信代码片段,我已经尝试了各种选项,包括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();
}

在另一种情况下,connection.setRequestMethod("GET")处出现异常。有什么提示吗?

尝试使用 conn.setDoOutput(false);。另请参见:https://dev59.com/nljUa4cB1Zd3GeqPPThV - Macchiatow
你想发送什么?GET - CONNECT 是你想要发送的内容吗? - hgoebl
为什么要为 GET 请求编写主体呢?使用 POST 有什么问题吗? - user207421
1个回答

2
以下代码运行正常: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);
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接