2010-11-15 147 views
0

我正尝试向使用Java的REST服务器发送GET请求。 这是一些调试的代码。Java - 在发送HTTP请求时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 

正如你所看到的,反应是空的。

但如果我尝试复制并粘贴在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 

你可以看到什么是错的?我怎样才能进一步调试此代码? 任何帮助将非常感激。

+2

你不调用'connection.connect();'是不是需要? – khachik 2010-11-15 12:43:46

回答

2

我想你不要使用HttpURLConnection(没有连接())。

也许研究这个example

+0

谢谢,您的链接已帮助 – dan 2010-11-15 13:20:27

相关问题