如何使用api登录reddit.com?

时间:2013-04-05 03:43:18

标签: html api post reddit

我不确定如何使用api格式化我的请求URL以登录reddit。我试过这个,但我得到一个页面找不到错误

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

1 个答案:

答案 0 :(得分: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() );
    }