繁体   English   中英

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

[英]Java - problems with REST client while sending an HTTP request

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

  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

如您所见,响应为空。

但是,如果我尝试将URL复制并粘贴到Firefox中,则会得到此输出

{"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())。

也许研究这个例子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM