【问题标题】:Why am I getting 'HTTP Version Not Supported' reply when I try to connect to a URL?当我尝试连接到 URL 时,为什么会收到“不支持 HTTP 版本”的回复?
【发布时间】:2013-01-12 09:39:16
【问题描述】:

下面的 sn-p 尝试连接到一个 url。该 url 还发送一个名为 FileNames 的参数。但是当我运行这个 sn-p 时,我总是得到一个HTTP Version Not Supported 的回复。可能是什么原因?

try {
  URL url = new URL(AddressInformation.clientAddressToSendFileNames + URLEncoder.encode(list.toString(), "UTF-8")); // STATEMENT-1
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();

  if(connection.getResponseCode() == 200) {
    // File names sent to the client that requested it
    System.out.println("File names sent");
  } else {
     // Error : While trying to send the file names
     System.out.println("Unable to send file names");
     System.out.println("RESPONSE CODE ------->>>>" + connection.getResponseMessage());
   }
} catch(Exception exc) {
   exc.printStackTrace();
  }

在STATEMENT-1中,AddressInformation.clientAddressToSendFileNames对应

http://localhost:8084/D Nappster/ReceiveFileNames?FileNames=

我正在运行 Tomcat 7。

【问题讨论】:

  • 对方发送的完整响应是什么?
  • @fge 我不明白你的意思
  • URL 可能是问题。尝试全部编码。您会注意到 URL 中 DNappster 之间的空格
  • 尝试将空间编码为%20
  • 试试http://localhost:8084/D%20Nappster/ReceiveFileNames?FileNames=

标签: java url tomcat httpresponse httpurlconnection


【解决方案1】:

您的 URL 似乎无效(其中包含一个空格),但 URL 构造函数没有检测到。

您可以改为使用 URI 的构造函数,它会为您正确编码,而无需担心,然后将其转换为 URL:

URI uri = new URI("http", null, "thehost", theport, "thepath", "thequery", null);
URL url = uri.toURL();

当然,这需要更改您的AddressInformation

有关详细信息,请参阅Javadoc

【讨论】:

  • 这个 URI 是否正确:URI uri = new URI("http",null,"localhost",8084,AddressInformation.clientAddressToSendFileNames,"FileNames="+list.toString(),null) ?
  • 其中 FileNames=foo 是查询字符串
  • 而字符串AddressInformation.clientAddressToSendFileNames‌​对应于D Nappster/ReceiveFileNames
  • 如果您的list 实际上是List,则不会这样做,因为.toString() 不会输出查询字符串中预期的格式。您需要一个实用函数来为您构建正确的查询字符串(无需转义任何内容,因为URI 再次为您执行此操作。此外,您需要在AddressInformation.clientAddressToSendFileNames 之前添加/
  • @saplingPro 您在快照中显示的所有内容似乎都是正确的,除了 DNappster 之间的空格!我注意到在上面的 cmets 中,即使 D%20Nappster 也会返回 Not Found 代码。此答案建议的自动编码将%20 置于DNappster 之间。在浏览器中运行此应用程序。浏览器如何显示 URL?并尝试该网址
【解决方案2】:

好吧,就我而言,我解决了这个问题,在 httpConnection.getResponseCode() 语句之前在我的 url 中进行了替换:用 %20 替换空格。

例如:

String url = "http://localhost:8080/Service/methodName?imagem=MY IMAGE NAME";
url = url.replace(" ", "%20");

替换后的url如下:

http://localhost:8080/Service/methodName?imagem=MY%20IMAGE%20NAME

为了测试一下,试试把url直接放到浏览器里。

【讨论】:

    猜你喜欢
    • 2017-12-27
    • 1970-01-01
    • 2015-11-27
    • 2015-01-24
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多