【问题标题】:REST HttpURLConnectionREST HttpURL 连接
【发布时间】:2013-08-13 00:45:05
【问题描述】:

我正在开发一个 REST 客户端,使用 HttpURLConnection 来试验 tinkerpop 数据库。

我正在尝试发送'GET - CONNECT'。现在我明白(来自一些网络研究)如果我使用doOutput(true),即使我setRequestMethod'GET' 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); 另见:stackoverflow.com/questions/6341602/…
  • 您要发送什么? GET - CONNECT是你要发送的正文吗?
  • 为什么要为 GET 请求写入正文?使用 POST 有什么问题?

标签: java web-services rest httpurlconnection


【解决方案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);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-25
    • 2012-07-09
    相关资源
    最近更新 更多