Android Open Source - Reddit-Underground Reddit Requestor






From Project

Back to project page Reddit-Underground.

License

The source code is released under:

This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a co...

If you think the Android project Reddit-Underground listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/*
 Copyright 2013 Cory Dissinger//from   ww w .  jav  a2  s .co m

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at 

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 */
package com.cd.reddit.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.cd.reddit.RedditException;
import com.cd.reddit.http.util.RedditRequestInput;
import com.cd.reddit.http.util.RedditRequestResponse;

import org.apache.commons.io.IOUtils;

/**
 * Necessary implementation of HttpURLConnection and friends.
 * Apache HTTP Client, while easier to use, is avoided to retain Android compatibility.
 * <br/> 
 * <br/>
 * Needs to have SSL/HTTPS support as well as further analysis of other needs.
 * 
 * @author <a href="https://github.com/corydissinger">Cory Dissinger</a>
 * @author <a href="https://github.com/cybergeek94">Austin Bonander</a>
 */
public class RedditRequestor {
  //TODO: Add ability to connect to ssl.reddit.com because credentials should not be in plain-text!
  private static final String HOST = "www.reddit.com";
  
  private final String userAgent;
  
  private String modhash = null;
    private String session = null;

    public RedditRequestor(String userAgent) {
        this.userAgent = userAgent;
    }
    
    private HttpURLConnection getConnection(RedditRequestInput input) throws RedditException {
        try {
            HttpURLConnection connection = (HttpURLConnection) generateURL(input.getPathSegments(), input.getQueryParams())
                    .openConnection();
            
            connection.setRequestProperty("User-Agent", userAgent);
            
            if(session != null)
              connection.setRequestProperty("Cookie", "reddit_session=" + session);

            if(modhash != null)
                connection.setRequestProperty("X-Modhash", modhash);
            
            return connection;
        } catch (Exception e) {
            throw new RedditException(e);
        }
    }

    public RedditRequestResponse executeGet(RedditRequestInput input) throws RedditException {
        return readResponse(getConnection(input), input);
    }

    public RedditRequestResponse executePost(RedditRequestInput input) throws RedditException {
        HttpURLConnection connection = getConnection(input);
        
        connection.setDoOutput(true);
        
        try {
      connection.setRequestMethod("POST");
    } catch (ProtocolException e) {
      throw new RedditException(e);
    }

        OutputStream outputStream = null;
        
        try {
            outputStream = connection.getOutputStream();
            IOUtils.write(generateUrlEncodedForm(input.getFormParams()), outputStream, "UTF-8");
        } catch (IOException e) {
            throw new RedditException(e);
        } finally {
            IOUtils.closeQuietly(outputStream);
        }

        return readResponse(connection, input);
    }

    private RedditRequestResponse readResponse(HttpURLConnection connection, RedditRequestInput input) throws RedditException {
        InputStream stream = null;

        try {
            // Connection will be made here
            stream = connection.getInputStream();

            // Buffers internally
            String responseBody = IOUtils.toString(stream, "UTF-8");
            int statusCode = connection.getResponseCode();

            if (statusCode != HttpURLConnection.HTTP_OK) {
                throw new RedditException(generateErrorString(statusCode, input, responseBody));
            }

            return new RedditRequestResponse(statusCode, responseBody);

        } catch (IOException e1) {
            throw new RedditException(e1);
        } finally {
            // Internally checks for null
            IOUtils.closeQuietly(stream);
        }
    }

    private String generateUrlEncodedForm(Map<String, String> formParams) {
        QueryBuilder builder = new QueryBuilder();

        for (Map.Entry<String, String> entry : formParams.entrySet()) {
            builder.addParameter(entry.getKey(), entry.getValue());
        }

        return builder.build();
    }

    private URL generateURL(List<String> pathSegments,
            Map<String, String> queryParams) throws MalformedURLException {

        String path = "";
        String query = "";

        if (pathSegments != null) {
            StringBuilder pathBuilder = new StringBuilder("/");
            Iterator<String> itr = pathSegments.iterator();

            while (itr.hasNext()) {
                pathBuilder.append(itr.next());

                if (itr.hasNext()) {
                    pathBuilder.append("/");
                }
            }

            path = pathBuilder.toString();
        }

        if (queryParams != null) {
            QueryBuilder builder = new QueryBuilder();

            for (Map.Entry<String, String> entry : queryParams.entrySet()) {
                builder.addParameter(entry.getKey(), entry.getValue());
            }

            query = "?" + builder.build();
    }
    
    return new URL("http", HOST, path+query);
  }

  public void setModhashHeader(String modhash) {
    this.modhash = modhash;
  }
  
    public void setSession(String session) {
        this.session = session;
    }

    private String generateErrorString(final int statusCode,
                           final RedditRequestInput input,
                           final String responseBody) {
      
        String nl = System.getProperty("line.separator");
        StringBuilder builder = new StringBuilder();

        builder.append("--- STATUS CODE ---");
        builder.append(nl);
        builder.append(statusCode);
        builder.append(nl);
        builder.append("--- REQUEST INPUT---");
        builder.append(nl);
        builder.append(input.toString());
        builder.append(nl);
        builder.append("--- RESPONSE BODY---");
        builder.append(nl);
        builder.append(responseBody);
        builder.append(nl);

        return builder.toString();
    }
}




Java Source Code List

com.cd.reddit.RedditException.java
com.cd.reddit.Reddit.java
com.cd.reddit.exception.RedditRateLimitException.java
com.cd.reddit.http.QueryBuilder.java
com.cd.reddit.http.RedditRequestor.java
com.cd.reddit.http.util.RedditApiParameterConstants.java
com.cd.reddit.http.util.RedditApiResourceConstants.java
com.cd.reddit.http.util.RedditRequestInput.java
com.cd.reddit.http.util.RedditRequestResponse.java
com.cd.reddit.json.jackson.RedditJacksonManager.java
com.cd.reddit.json.jackson.RedditJsonParser.java
com.cd.reddit.json.mapping.RedditAccount.java
com.cd.reddit.json.mapping.RedditComment.java
com.cd.reddit.json.mapping.RedditJsonMessage.java
com.cd.reddit.json.mapping.RedditLink.java
com.cd.reddit.json.mapping.RedditMessage.java
com.cd.reddit.json.mapping.RedditMore.java
com.cd.reddit.json.mapping.RedditSubreddit.java
com.cd.reddit.json.mapping.RedditType.java
com.cd.reddit.json.util.RedditComments.java
com.cd.reddit.json.util.RedditJsonConstants.java
com.mikedaguillo.reddit_underground.ApplicationTest.java
com.mikedaguillo.reddit_underground.ImageViewScreen.java
com.mikedaguillo.reddit_underground.LoginScreen.java
com.mikedaguillo.reddit_underground.ManualEntryScreen.java
com.mikedaguillo.reddit_underground.RedditInstance.java
com.mikedaguillo.reddit_underground.RedditListItem.java
com.mikedaguillo.reddit_underground.SavedSubredditsScreen.java
com.mikedaguillo.reddit_underground.StartScreen.java
com.mikedaguillo.reddit_underground.SubredditsSelectionScreen.java
com.mikedaguillo.reddit_underground.TinyDB.java
com.mikedaguillo.reddit_underground.SubredditDatabaseModel.SubredditsDatabaseHelper.java