Reputation: 235
I have been researching this however I can't seem to correct the error.I'm only new in android development. I have a "The Method is undefined for the type object" error on both getStatusCode()
and getReasonPhrase()
. Any help would be appreciated.
package com.javapapers.java.io;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class HttpUtil {
public String getHttpResponse(HttpRequestBase request) {
String result = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpResponse httpResponse = httpClient.execute(request);
int statusCode = httpResponse.getStatusLine().getStatusCode();
String reason = httpResponse.getStatusLine().getReasonPhrase();
StringBuilder sb = new StringBuilder();
if (statusCode == 200) {
HttpEntity entity = httpResponse.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader bReader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"), 8);
String line = null;
while ((line = bReader.readLine()) != null) {
sb.append(line);
}
} else {
sb.append(reason);
}
result = sb.toString();
} catch (UnsupportedEncodingException ex) {
} catch (ClientProtocolException ex1) {
} catch (IOException ex2) {
}
return result;
}
}
I was then told that I shouldn't use the Apache HTTP client but use HttpURLConnection instead so I changed my code and I'm wondering would this work and would the outcome be the same
public class HttpUtil {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println("Usage: java Reverse "
+ "https://twitter.com/aaroadwatch"
+ " string_to_reverse");
System.exit(1);
}
String stringToReverse = URLEncoder.encode(args[1], "UTF-8");
URL url = new URL(args[0]);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream());
out.write("string=" + stringToReverse);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
}
}
or even something like this
URL url = new URL("https://twitter.com/aaroadwatch");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
}
My Twitter API Class
I have an error on getHttpResponse
and getHttpResponse
package com.javapapers.social.twitter;
import android.util.Base64;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.javapapers.java.io.HttpUtil;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
public class TwitterAPI {
private String twitterApiKey;
private String twitterAPISecret;
final static String TWITTER_TOKEN_URL = "https://api.twitter.com/oauth2/token";
final static String TWITTER_STREAM_URL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";
public TwitterAPI(String twitterAPIKey, String twitterApiSecret){
this.twitterApiKey = twitterAPIKey;
this.twitterAPISecret = twitterApiSecret;
}
public ArrayList<TwitterTweet> getTwitterTweets(String screenName) {
ArrayList<TwitterTweet> twitterTweetArrayList = null;
try {
String twitterUrlApiKey = URLEncoder.encode(twitterApiKey, "UTF-8");
String twitterUrlApiSecret = URLEncoder.encode(twitterAPISecret, "UTF-8");
String twitterKeySecret = twitterUrlApiKey + ":" + twitterUrlApiSecret;
String twitterKeyBase64 = Base64.encodeToString(twitterKeySecret.getBytes(), Base64.NO_WRAP);
TwitterAuthToken twitterAuthToken = getTwitterAuthToken(twitterKeyBase64);
twitterTweetArrayList = getTwitterTweets(screenName, twitterAuthToken);
} catch (UnsupportedEncodingException ex) {
} catch (IllegalStateException ex1) {
}
return twitterTweetArrayList;
}
public ArrayList<TwitterTweet> getTwitterTweets(String screenName,
TwitterAuthToken twitterAuthToken) {
ArrayList<TwitterTweet> twitterTweetArrayList = null;
if (twitterAuthToken != null && twitterAuthToken.token_type.equals("bearer")) {
HttpGet httpGet = new HttpGet(TWITTER_STREAM_URL + screenName);
httpGet.setHeader("Authorization", "Bearer " + twitterAuthToken.access_token);
httpGet.setHeader("Content-Type", "application/json");
HttpUtil httpUtil = new HttpUtil();
String twitterTweets = httpUtil.getHttpResponse(httpGet);
twitterTweetArrayList = convertJsonToTwitterTweet(twitterTweets);
}
return twitterTweetArrayList;
}
public TwitterAuthToken getTwitterAuthToken(String twitterKeyBase64) throws UnsupportedEncodingException {
HttpPost httpPost = new HttpPost(TWITTER_TOKEN_URL);
httpPost.setHeader("Authorization", "Basic " + twitterKeyBase64);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
HttpUtil httpUtil = new HttpUtil();
String twitterJsonResponse = httpUtil.getHttpResponse(httpPost);
return convertJsonToTwitterAuthToken(twitterJsonResponse);
}
private TwitterAuthToken convertJsonToTwitterAuthToken(String jsonAuth) {
TwitterAuthToken twitterAuthToken = null;
if (jsonAuth != null && jsonAuth.length() > 0) {
try {
Gson gson = new Gson();
twitterAuthToken = gson.fromJson(jsonAuth, TwitterAuthToken.class);
} catch (IllegalStateException ex) { }
}
return twitterAuthToken;
}
private ArrayList<TwitterTweet> convertJsonToTwitterTweet(String twitterTweets) {
ArrayList<TwitterTweet> twitterTweetArrayList = null;
if (twitterTweets != null && twitterTweets.length() > 0) {
try {
Gson gson = new Gson();
twitterTweetArrayList =
gson.fromJson(twitterTweets, new TypeToken<ArrayList<TwitterTweet>>(){}.getType());
} catch (IllegalStateException e) {
}
}
return twitterTweetArrayList;
}
private class TwitterAuthToken {
String token_type;
String access_token;
}
}
Upvotes: 1
Views: 4978
Reputation: 4147
This is a possible implementation exploiting HttpUrlConnection
:
private static final int CONNECTION_TIMEOUT = (int) TimeUnit.SECONDS.toMillis(15);
private static final int READ_TIMEOUT = (int) TimeUnit.SECONDS.toMillis(15);
public static void main(String[] args) {
String address = "https://twitter.com/aaroadwatch";
System.out.println(get(address));
}
public static String get(String address) {
String result = null;
HttpURLConnection conn = null;
InputStream in = null;
try {
// building api url
URL url = new URL(address);
System.out.println("GET URL " + url.toString());
// establishing connection with server
conn = (HttpURLConnection) url.openConnection();
// building headers
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
in = new BufferedInputStream(conn.getInputStream());
// building output string from stream
StringBuilder sb = new StringBuilder();
int b;
while ((b = in.read()) != -1) {
sb.append((char) b);
}
String output = sb.toString().replace("\n", "");
System.out.println("GET RES " + output);
result = output;
}
} catch (MalformedURLException ex) {
System.err.println("malformed url");
ex.printStackTrace();
} catch (IOException ex) {
System.err.println("I/O exception");
ex.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
}
}
if (conn != null) {
conn.disconnect();
}
}
return result;
}
Hope this could help.
Upvotes: 3