2011-11-14 11 views
5

Sto provando a utilizzare l'API Reddit per fare qualcosa. Ho tutto funzionante ma cambio pagina e accesso.Non riesco a utilizzare le API di Reddit per accedere

Ho bisogno di accedere per usare il mio programma, so come usare il cookie che ottengo, ma non riesco proprio ad accedere.

Ecco il codice:

public static Login POST(URL url, String user, String pw) throws IOException 
{ 

    String encodedData = URLEncoder.encode("api_type=json&user=" + user +"&passwd="+pw, "UTF-8"); 
    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"); 
    PrintWriter out = new PrintWriter(ycConnection.getOutputStream()); 


    out.print(encodedData.getBytes()); 
    out.close(); 

    BufferedReader in = new BufferedReader(new InputStreamReader(ycConnection.getInputStream())); 
    String response = in.readLine(); 

    Map<String, List<String>> headers = ycConnection.getHeaderFields(); 
    List<String> values = headers.get("Set-Cookie"); 
    String cookieValue = null; 
    for (java.util.Iterator<String> iter = values.iterator(); iter.hasNext();) { 
     String v = iter.next(); 
     if (cookieValue == null) 
      cookieValue = v; 
     else 
      cookieValue = cookieValue + ";" + v; 
    } 

    return new Login(cookieValue, response); 
} 

Il più tipico eccezione che ottengo è:

java.io.IOException: Server ha restituito il codice di risposta HTTP: 504 per l'URL: http://www.reddit.com/api/login/kagnito/ al sole. net.www.protocol.http.HttpURLConnection.getInputStream (sorgente sconosciuta)

Ma ho anche ricevuto un sacco di "pa invalid ssword "messaggi.

Come posso risolvere questo? Ci sono stato per ore!

Btw. Questo è quello che ho problemi di comprensione: https://github.com/reddit/reddit/wiki/API%3A-login Non sono sicuro di come POST questo? Dovrebbe andare nell'intestazione, o? Non sono così familiare con il protocollo HTTP. (Da qui il mio progetto - sto imparando)

+0

Controllare un aggiornamento per la mia risposta – Strelok

risposta

9

Senza entrare troppo sul perché il resto non potrebbe funzionare, c'è un problema in che siete:

  • Utilizzando URLEncoder per codificare il pubblicare i dati: i tuoi dati dei post non entreranno nell'URL, quindi non codificarli.

  • Non si sta impostando l'intestazione Content-Length.

Ecco quello che si dovrebbe avere per iniziare:

public static Login POST(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", data.length()); 

    PrintWriter out = new PrintWriter(ycConnection.getOutputStream()); 


    out.print(data.getBytes()); 
    out.close(); 

    BufferedReader in = new BufferedReader(new InputStreamReader(ycConnection.getInputStream())); 
    String response = in.readLine(); 

    Map<String, List<String>> headers = ycConnection.getHeaderFields(); 
    List<String> values = headers.get("Set-Cookie"); 
    String cookieValue = null; 
    for (java.util.Iterator<String> iter = values.iterator(); iter.hasNext();) { 
     String v = iter.next(); 
     if (cookieValue == null) 
      cookieValue = v; 
     else 
      cookieValue = cookieValue + ";" + v; 
    } 

    return new Login(cookieValue, response); 
} 

Quando si lavora con le API come questo, si dovrebbe sicuramente installare Fiddler che è debugger HTTP. Avresti immediatamente visto il problema dato che i tuoi dati post non assomigliano affatto all'esempio.

UPDATE:

Ecco un piccolo codice che ho appena buttato in un test e autenticati me più che bene (ovviamente cambiare myusername e mypassword alla tua (non dimenticare di cambiare l'URL troppo):..

@Test 
    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()); 
    } 
+0

Tutto quello che ha detto ha fatto il buon senso, e ora ho cambiato il codice per quel Tutto ciò che viene dopo out.close() ad eccezione del servire La risposta è irrilevante, non è ancora il problema, quindi grazie per non esservi immersi. Ma il problema persiste, non posso essere autenticato. –

+0

Si prega di ignorare la cattiva sillaba, non ho dormito molto stanotte. –

+0

Grazie mille! Ha funzionato! Leggero il tuo codice e lo capirò, prima di andare avanti. Ma davvero, grazie! –

Problemi correlati