开发者

Java - problems with REST client while sending an HTTP request

I am trying to send a GET request to a REST server using Java. This is the code with some debugging.

  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");
  }

This is the output:

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

As you can see, the response is empty.

But if I try and copy and paste the URL in Firefox I get this output

{"error":220}

and this header:

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

Can you see what it is wrong? How could I debug this code further?开发者_运维问答 Any help would be very much appreciated.


I think you do not use HttpURLConnection properly (there is no connect()).

Maybe study this example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜