2013-04-05 106 views
0

我不知道如何格式化我的請求URL以使用api登錄到reddit。我試過這個,但我只是得到一個頁面沒有找到錯誤如何使用api登錄到reddit.com?

https://ssl.reddit.com/api/login/?user=myusername&passwd=mypassword&api_type=json 
+0

你怎麼'後'這個?你的代碼的其餘部分在哪裏?你不只是把它粘貼到你的瀏覽器的地址欄中吧? – couzzi 2013-04-05 04:26:29

+0

那麼這就是我正在測試它......我期待找回一些JSON作爲迴應。 – James 2013-04-05 04:33:31

+0

但是這是一個'POST'請求 - 你需要'POST'到那個URL。 'GET' vars-你正在使用的 - 不會在這裏工作。 – couzzi 2013-04-05 04:50:42

回答

0

請參閱this question。用戶Strelok有一個很好的答案

public void someTest() throws IOException 
    { 
     URL u = new URL("https://ssl.reddit.com/api/login/myusername"); 
     login(u, "myusername", "mypassword"); 
    } 

    public static void login(URL url, String user, String pw) throws IOException 
    { 

     String data = "api_type=json&user=" + user + "&passwd=" + pw; 
     HttpURLConnection ycConnection = null; 
     ycConnection = (HttpURLConnection) url.openConnection(); 
     ycConnection.setRequestMethod("POST"); 
     ycConnection.setDoOutput(true); 
     ycConnection.setUseCaches(false); 
     ycConnection.setRequestProperty("Content-Type", 
      "application/x-www-form-urlencoded; charset=UTF-8"); 
     ycConnection.setRequestProperty("Content-Length", String.valueOf(data.length())); 

     DataOutputStream wr = new DataOutputStream(
      ycConnection.getOutputStream()); 
     wr.writeBytes(data); 
     wr.flush(); 
     wr.close(); 
     InputStream is = ycConnection.getInputStream(); 
     BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 
     String line; 
     StringBuffer response = new StringBuffer(); 
     while ((line = rd.readLine()) != null) 
     { 
      response.append(line); 
      response.append('\r'); 
     } 
     for (Entry< String, List<String>> r : ycConnection.getHeaderFields().entrySet()) 
     { 
      System.out.println(r.getKey() + ": " + r.getValue()); 
     } 
     rd.close(); 
     System.out.println(response.toString()); 
    }