public
Fork of fbrunel/twitterdroid
Description: Present.ly Android is the official Android client for Present.ly.
Homepage:
Clone URL: git://github.com/presently/presently-android.git
presently-android / presently-android / src / jtwitter / TwitterConnection.java
100644 197 lines (170 sloc) 7.0 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package jtwitter;
 
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
 
import javax.xml.parsers.ParserConfigurationException;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.util.encoders.Base64;
import org.xml.sax.SAXException;
 
import android.util.Log;
 
/**
* TwitterRequestSender sends http requests to the Twitter web service.
*
* @author Lukasz Grzegorz Maciak
*
*/
 
public class TwitterConnection {
 
    private static String PUBLIC_TIMELINE_URL = "presentlyapp.com/api/twitter/statuses/public_timeline.xml";
    private static String FRIENDS_TIMELINE_URL = "presentlyapp.com/api/twitter/statuses/friends_timeline.xml";
    private static String UPDATE_URL = "presentlyapp.com/api/twitter/statuses/update.xml";
    private static String USER_AGENT = "Mozilla/4.5";
    private static String PROTOCOL = "https://";
    private static String TAG = "TwitterConnection";
 
    private String username;
    private String password;
    private String subdomain;
 
    public TwitterConnection(String subdomain, String username, String password) {
        this.subdomain = subdomain;
        this.username = username;
        this.password = password;
    }
 
    /**
* Get the public timeline in XML format.
*
* @return TwitterResponse containing the public timeline entries
* @throws IOException
*/
    public TwitterResponse getPublicTimeline() throws Exception {
        return new TwitterResponse().parse(getRequest(PUBLIC_TIMELINE_URL));
    }
 
    /**
* Get the user's friends timeline (what you see on the homepage) with basic
* authentication.
*
* @return TwitterResponse containing the friends timeline entries
* @throws IOException
*/
    public TwitterResponse getFriendsTimeline() throws ParseException, SAXException, ParserConfigurationException, IOException, TwitterConnectionException {
        return new TwitterResponse().parse(getRequest(FRIENDS_TIMELINE_URL));
    }
 
    /**
* Update your Twitter status.
*
* @param text
* String containing text you want to update your status with
* @return TwitterResponse containing response from Twitter server
* @throws IOException
*/
    public TwitterResponse updateStatus(String text) throws ParseException, SAXException, ParserConfigurationException, IOException, TwitterConnectionException {
        TwitterResponse twitterResponse = null;
        if (text.length() > 140) {
            throw new IllegalArgumentException("Update text is longer than 140 characters");
        }
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("status", text));
        twitterResponse = new TwitterResponse().parse(postRequest(UPDATE_URL, new UrlEncodedFormEntity(nvps)));
 
        return twitterResponse;
    }
 
    /**
* Sends a GET request to Present.ly
*
* @param resource
* @return String response from the server
*/
    private String getRequest(String resource) {
        String result = null;
        String url = PROTOCOL + subdomain + "." + resource;
        Log.d(TAG, "GET: " + url);
 
        HttpClient client = new DefaultHttpClient(new BasicHttpParams());
        HttpGet getMethod = new HttpGet((url));
        try {
            getMethod.setHeader("User-Agent", USER_AGENT);
            getMethod.addHeader("Authorization", "Basic " + getCredentials());
 
            HttpResponse httpResponse = client.execute(getMethod);
            result = retrieveInputStream(httpResponse.getEntity());
 
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
            e.printStackTrace();
        } finally {
            getMethod.abort();
        }
        return result;
    }
 
    /**
* Sends a POST request to Present.ly
*
* @param resource
* @param formParams UrlEncodedFormEntity which is comprised of a List of NameValuePairs
* @return String response from the server
*/
    private String postRequest(String resource, UrlEncodedFormEntity formParams) throws SocketTimeoutException, SocketException {
        String result = null;
        String url = PROTOCOL + subdomain + "." + resource;
        Log.d(TAG, "POST: " + url);
 
        HttpClient client = new DefaultHttpClient(new BasicHttpParams());
        HttpPost postMethod = new HttpPost((url));
        try {
            postMethod.setHeader("User-Agent", USER_AGENT);
            postMethod.addHeader("Authorization", "Basic " + getCredentials());
 
            if (formParams != null)
                postMethod.setEntity(formParams);
 
            HttpResponse httpResponse = client.execute(postMethod);
            result = EntityUtils.toString(httpResponse.getEntity());
 
            if (result != null)
                Log.d(TAG, "Returned response [" + httpResponse.getStatusLine() + "] from the server: " + result);
 
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
            e.printStackTrace();
        } finally {
            postMethod.abort();
        }
        return result;
    }
 
    /**
* Retrieves the content input stream from a GET request
*
* @param httpEntity
* @return
*/
    private String retrieveInputStream(final HttpEntity httpEntity) {
        int length = (int) httpEntity.getContentLength();
        StringBuffer stringBuffer = new StringBuffer(length);
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8);
            char buffer[] = new char[length];
            int count;
 
            while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) {
                stringBuffer.append(buffer, 0, count);
            }
        } catch (UnsupportedEncodingException e) {
            Log.e(TAG, e.getMessage());
            e.printStackTrace();
        } catch (IllegalStateException e) {
            Log.e(TAG, e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            Log.e(TAG, e.getMessage());
            e.printStackTrace();
        }
        return stringBuffer.toString();
    }
 
    private String getCredentials() {
        return new String(Base64.encode((username + ":" + password).getBytes()));
    }
}