Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java-发送HTTP请求时REST客户端出现问题_Java_Http - Fatal编程技术网

Java-发送HTTP请求时REST客户端出现问题

Java-发送HTTP请求时REST客户端出现问题,java,http,Java,Http,我正在尝试使用Java向REST服务器发送GET请求。 这是经过一些调试的代码 URL url = new URL(request); System.out.println("request url: " + url.toString()); System.out.println("method: " + httpMethod); HttpURLConnection connection = (HttpURLConnection) url.openConnection();

我正在尝试使用Java向REST服务器发送GET请求。 这是经过一些调试的代码

  URL url = new URL(request); 

  System.out.println("request url: " + url.toString());
  System.out.println("method: " + httpMethod);

  HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
  connection.setDoOutput(true); 
  connection.setInstanceFollowRedirects(false); 
  connection.setRequestMethod(httpMethod); 
  connection.setRequestProperty("Content-Type", "text/plain"); 
  connection.setRequestProperty("charset", "utf-8"); 

  OutputStream os = connection.getOutputStream(); 
  os.flush();
  String response = os.toString(); 

  System.out.println("response: " + response);      

  if (response.length() == 0)
  {
      throw new MyException("the response is empty");
  }
这是输出:

request url: http://www.example.com/api.php/getToken/?api_ver=1&token=&api_key=bf8de053d9b6c540fb12195b4ac1602b0a71788c&sig=e00a59747afc7232207d40087e3765a5
method: GET
response: 
com.example.api.client.MyException: the response is empty
如您所见,响应是空的

但是如果我尝试在Firefox中复制并粘贴URL,我会得到这个输出

{"error":220}
这个标题是:

HTTP/1.1 200 OK
Date: Mon, 15 Nov 2010 11:55:29 GMT
Server: Apache
Cache-Control: max-age=0
Expires: Mon, 15 Nov 2010 11:55:29 GMT
Vary: Accept-Encoding,User-Agent
Content-Encoding: gzip
Content-Length: 33
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=utf-8
你能看出哪里不对吗?如何进一步调试此代码?
非常感谢您的帮助。

我认为您没有正确使用HttpURLConnection(没有connect())


也许可以研究一下。

您不需要调用
connection.connect()不需要吗?