I'm trying to implement support for Woocommerce e-shop into our system and I'm using scribe-java for that. What I'm trying is to get Json response from e-shop and store it into database.
Problem is that I can connect to e-shop but instead of Json response, I get HTML response. Any help would be much appreciated. BTW, I'm using latest scribe-java 3.0.0
URL: http://shop_url/wp-json/wc/v1/orders?after=2016-08-17T00:00:00&page=1&per_page=100&order=asc
Here's source code:
private Integer callGETWithOAuthAuthentication(String url, StringBuffer sbRet) throws IOException {
OAuth10aService service = new ServiceBuilder()
.apiKey(getSettingsStr().getSecret1())
.apiSecret(getSettingsStr().getSecret2())
.debugStream(System.out)
.signatureType(SignatureType.QueryString)
.build(WooCommerceApi.instance());
OAuthRequest request = new OAuthRequest(Verb.GET, url, service);
service.signRequest( new OAuth1AccessToken("", ""), request);
Response response = request.send();
BufferedReader in = new BufferedReader(
new InputStreamReader(response.getStream()));
String inputLine;
StringBuffer responseJson = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
responseJson.append(inputLine);
}
if (sbRet != null) {
sbRet.append(responseJson.toString());
}
return response.getCode();
}
And here is WooCommerceApi
import com.github.scribejava.core.builder.api.DefaultApi10a;
import com.github.scribejava.core.model.OAuth1RequestToken;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.services.HMACSha1SignatureService;
import com.github.scribejava.core.services.SignatureService;
public class WooCommerceApi extends DefaultApi10a {
protected WooCommerceApi() {
}
private static class InstanceHolder {
private static final WooCommerceApi INSTANCE = new WooCommerceApi();
}
public static WooCommerceApi instance() {
return InstanceHolder.INSTANCE;
}
#Override
public String getAccessTokenEndpoint() {
return null;
}
#Override
public String getRequestTokenEndpoint() {
return null;
}
#Override
public Verb getAccessTokenVerb() {
return Verb.GET;
}
#Override
public Verb getRequestTokenVerb() {
return Verb.GET;
}
#Override
public String getAuthorizationUrl(OAuth1RequestToken requestToken) {
// TODO Auto-generated method stub
return null;
}
#Override
public SignatureService getSignatureService() {
return new HMACSha1SignatureService();
}
}
And this is a response I'm getting:
`<!DOCTYPE html>
<!--[if IE 6]>
<html id="ie6" lang="sl-SI">
<![endif]-->
<!--[if IE 7]>
<html id="ie7" lang="sl-SI">
<![endif]-->
<!--[if IE 8]>
<html id="ie8" lang="sl-SI">
<![endif]-->
<!--[if !(IE 6) | !(IE 7) | !(IE 8) ]><!-->
<html lang="sl-SI">
<!--<![endif]-->
<head>`
Related
In Android is there a better way than using a single AsyncTask with a parameter to work out which REST endpoint to call?
e.g. I need to call:
www.test.com/api/room/id
www.test.com/api/room/id/booking
AsyncTask is designed for a single doInBackground() method that does a single thing, e.g. call:
www.test.com/api/room/id
I don't want to create multiple AsyncTasks instances, one for each REST endpoint.
The back end would use:
RoomClient = new RoomClient();
roomClient.getID()
roomClient.getBookingForRoom()
In Android it looks like I'd need
class RoomFromId extends AsyncTask
...
call www.test.com/api/room/id
class BookingForRoom extends AsyncTask
..
call www.test.com/api/room/id/booking
What I'd ideally like in the Android app is the idiom of writing a rest client that can call all REST endpoints in the background, without having to do each one in its own AsyncTask. I'd prefer to use what Android has, rather than a 3rd party library.
Create a generic Class extends from AsyncTask that return response in a generic type that extends from YourBaseModel (I called it M)
public class HttpRequest<M extends BaseModel> extends AsyncTask<Object, Integer, M> {
public enum RequestMethod {
GET("GET"), POST("POST");
private final String requestMethod;
RequestMethod(String requestMethod) {
this.requestMethod = requestMethod;
}
public String getValue() {
return requestMethod;
}
}
private Context context = null;
private String url;
private OnResponseCallback onResponseCallback;
private OnFailureCallback onFailureCallback;
private RequestMethod method;
private int statusCode;
private String message;
private Class<M> responseModel;
private Object body = null;
private String token;
private HttpRequest() {
}
#Override
protected M doInBackground(Object... voids) {
try {
HttpURLConnection connection = getHttpConnection();
connection.connect();
int statusCode = connection.getResponseCode();
if (connection.getResponseCode() / 100 != 2) {
this.statusCode = statusCode;
this.message = connection.getResponseMessage();
return JsonParser.getErrorBodyAs(responseModel, statusCode,
message);
}
InputStreamReader streamReader = new
InputStreamReader(connection.getInputStream());
return JsonParser.getErrorBodyAs(responseModel, statusCode,
convertInputStreamToString(streamReader));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private HttpURLConnection getHttpConnection() throws IOException {
URL url = new URL(this.url);
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setRequestMethod(method.getValue());
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "Bearer " + token);
connection.setReadTimeout(30000);
connection.setConnectTimeout(30000);
if (method == RequestMethod.POST) {
connection.setDoInput(true);
connection.setDoOutput(true);
if (body != null) {
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(new Gson().toJson(body));
writer.flush();
}
}
return connection;
}
#Override
protected void onPostExecute(M m) {
if (m == null) {
if ((message != null && !message.equals("") && statusCode != 0)) {
HttpException httpException = new HttpException(statusCode, message);
onFailureCallback.onFailure(httpException);
} else {
onFailureCallback.onFailure("unknown error");
}
} else {
onResponseCallback.onResponse(m);
}
}
public static String convertInputStreamToString(InputStreamReader inputStreamReader) throws IOException {
if (inputStreamReader == null) {
return "";
}
BufferedReader reader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String inputLine;
String result;
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
reader.close();
inputStreamReader.close();
return stringBuilder.toString();
}
static public class Builder {
HttpRequest t = new HttpRequest();
public Builder setContext(Context context) {
t.context = context;
return this;
}
public Builder setUrl(String url) {
t.url = url;
return this;
}
public Builder setRequestMethod(RequestMethod method) {
t.method = method;
return this;
}
public Builder setBody(Object body) {
t.body = body;
return this;
}
public Builder setToken(String token) {
t.token = token;
return this;
}
public HttpRequest get() {
return t;
}
public HttpRequest run(Class<?> responseTypeClass,
OnResponseCallback onResponseCallback,
OnFailureCallback onFailureCallback) {
t.responseModel = responseTypeClass;
t.onResponseCallback = onResponseCallback;
t.onFailureCallback = onFailureCallback;
t.execute();
return t;
}
public Builder() {
}
}
}
You can use it like this:
HttpRequest.Builder builder = new HttpRequest.Builder();
builder.setContext(context)
.setRequestMethod(HttpRequest.RequestMethod.POST)
.setBody(body)
.setUrl("http://url")
.run(YourResponeModel.class, new OnResponseCallback() {
#Override
public void onResponse(Object response) {
},
new OnFailureCallback() {
#Override
public void onFailure(Object throwable) {
}
});
In the class you create that extends AsyncTask you can create a constructor and pass whatever you want/need.
In this case you can define a class ApiManager that extends AsyncTask and pass a constant that defines the method to call.
In that constructor you can save the variable to your ApiManager object and then check it in the doInBackground method.
So, to call the room/id you could do something like:
new ApiManager(ROOM_FROM_ID).execute(...
And to call the room/id/booking:
new ApiManager(BOOKING_FOR_ROOM).execute(...
And the ApiManager class should be something like:
class ApiManager extends AsyncTask... {
private int method;
public ApiManager(int method) {
this.method = method;
}
...
}
Following Google's pagespeed advice I would like the minify the HTML responses of my Spring application. I don't mean GZip, I mean removing comments and whitespace from HTML before it is sent down the wire.
I would like to do this dynamically and not in my templates. My templates contain many comments that are useful but should not be part of the response.
Following is my controller;
#Controller
public class IndexController {
#GetMapping("/")
public ModelAndView index() {
Data data = ....
return new ModelAndView("index", data);
}
}
I managed to do this by adding a javax.servlet.Filter component that is using com.googlecode.htmlcompressor into Spring
First the Filter;
#Component
public class HtmlFilter implements Filter {
protected FilterConfig config;
public void init(FilterConfig config) throws ServletException {
this.config = config;
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws ServletException, IOException {
ServletResponse newResponse = response;
if (request instanceof HttpServletRequest) {
newResponse = new CharResponseWrapper((HttpServletResponse) response);
}
chain.doFilter(request, newResponse);
if (newResponse instanceof CharResponseWrapper) {
String text = newResponse.toString();
if (text != null) {
HtmlCompressor htmlCompressor = new HtmlCompressor();
response.getWriter().write(htmlCompressor.compress(text));
}
}
}
}
and relevant CharResponseWrapper;
class CharResponseWrapper extends HttpServletResponseWrapper {
protected CharArrayWriter charWriter;
protected PrintWriter writer;
protected boolean getOutputStreamCalled;
protected boolean getWriterCalled;
public CharResponseWrapper(HttpServletResponse response) {
super(response);
charWriter = new CharArrayWriter();
}
public ServletOutputStream getOutputStream() throws IOException {
if (getWriterCalled) {
throw new IllegalStateException("getWriter already called");
}
getOutputStreamCalled = true;
return super.getOutputStream();
}
public PrintWriter getWriter() throws IOException {
if (writer != null) {
return writer;
}
if (getOutputStreamCalled) {
throw new IllegalStateException("getOutputStream already called");
}
getWriterCalled = true;
writer = new PrintWriter(charWriter);
return writer;
}
public String toString() {
String s = null;
if (writer != null) {
s = charWriter.toString();
}
return s;
}
}
Works fantastically. Converts an html this ugly;
<!DOCTYPE HTML>
<html>
<head>
<title>
A Simple
<!-- Test-->
HTML Document
<!-- Test-->
</title>
</head>
<body>
<p>This is a very simple HTML document</p>
<!-- Test-->
<p>It only has two<!-- Test--> paragraphs</p>
<!-- Test-->
</body>
</html>
into this;
<!DOCTYPE HTML> <html> <head> <title> A Simple HTML Document </title> </head> <body> <p>This is a very simple HTML document</p> <p>It only has two paragraphs</p> </body> </html>
I've recently used AsyncTask into my android app and what this piece of code is doing, is making a get request to the provided url, and retrieving the song name from it. (The URL is a Spotify song). When I print out the response I am getting, it says
com.(projectname).(projectname).TRetrieve$HttpGetRequest#aed19ea
(TRetrieve is the name of the class that is doing this request)
How can I make the request and properly get the name of the song back?
This is the code for the class so far:
public class HttpGetRequest extends AsyncTask<String, Void, String> {
public static final String REQUEST_METHOD = "GET";
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
#Override
protected String doInBackground(String... params){
String stringUrl = "https://open.spotify.com/track/5Q41NLTmGbVPozwHKK7bk2";
String result;
String inputLine;
try {
URL myUrl = new URL(stringUrl);
HttpURLConnection connection = (HttpURLConnection)
myUrl.openConnection();
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.connect();
InputStreamReader streamReader = new
InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
result = stringBuilder.toString();
linkLoc = result.indexOf(testString) + testString.length();
for (int i = linkLoc; i < result.indexOf("on Spotify"); i++) {
sname += result.charAt(i) + "";
}
}
catch(IOException e){
e.printStackTrace();
sname = "Error";
}
return sname;
}
protected void onPostExecute(String result){
super.onPostExecute(result);
}
Interacting with API using AsyncTask / HttpURLConnection is very old-school. I suggest yo to use modern way to do it, using RxJava / Retrofit / Gson
1). Adding necessary dependencies
Add next dependencies to your <root>/app/build.gradle:
compile 'com.squareup.okhttp3:okhttp:3.3.1'
compile ('com.squareup.retrofit2:retrofit:2.0.2')
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
compile 'com.google.code.gson:gson:2.4'
compile 'io.reactivex:rxjava:1.0.13'
compile 'io.reactivex:rxandroid:0.25.0'
2). Creating HTTP client
2.1)* (This is optional, only if you need to send AUTH token in headers)
Create interceptor:
import com.betcade.sdk.util.AuthUtil;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class DBQRequestInterceptor implements Interceptor {
public DBQRequestInterceptor(){
}
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder();
if(<if necessary to send a token>){
requestBuilder.addHeader(<TOKEN_HEADER_NAME>, <TOKEN>);
}
Request request = requestBuilder.build();
return chain.proceed(request);
}
}
2.2)* (Also, optional step, only if you want to log request/response)
Create logging interceptor:
HttpLoggingInterceptor interceptor1 = new HttpLoggingInterceptor();
interceptor1.setLevel(HttpLoggingInterceptor.Level.BODY);
2.3) Create HTTP client
OkHttpClient client = new OkHttpClient.Builder()
.writeTimeout(8, TimeUnit.SECONDS)
.readTimeout(8, TimeUnit.SECONDS)
.addInterceptor(interceptor) // interceptor from step 2.1
.addInterceptor(interceptor1) // interceptor from step 2.2
.build();
2.4). Create TrackResponse model:
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class TrackResponse {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
/**
*
* #return
* The id
*/
public String getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(String id) {
this.id = id;
}
/**
*
* #return
* The name
*/
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
public void setName(String name) {
this.name = name;
}
}
2.5) Create interface ApiClient:
public interface ApiClient {
#GET("tracks/{id}")
Observable<TrackResponse> getTrackInfo(#Path("id") String trackId);
}
2.6). Creat instance of ApiClient:
Retrofit API = new Retrofit.Builder()
.client(client)
.baseUrl("https://api.spotify.com/v1/")
.addConverterFactory(GsonConverterFactory.create(new Gson()))
.addCallAdapterFactory(RxErrorHandlingCallAdapterFactory.create())
.build();
ApiClient client = API.create(ApiClient.class);
2.7). Getting the name:
client.getTrackInfo("5Q41NLTmGbVPozwHKK7bk2")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<TrackResponse>() {
#Override
public void call(TrackResponse trackResponse) {
String name = track.getName();
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable throwable) {
throwable.printStackTrace();
}
});
I'm really stumped with this one:
This is my method to create a dynamic image.
private Image createImage(final String id, final byte[] imageData){
NonCachingImage chartImage=new NonCachingImage(id) {
private static final long serialVersionUID = 1L;
#Override
protected IResource getImageResource() {
return new DynamicImageResource(){
private static final long serialVersionUID=1L;
#Override
protected byte[] getImageData(Attributes attributes) {
String myImageStr = new StringBuffer(
WicketApplication.TOMCAT_IMAGE_DOC_BASE).
append("13835.jpg").toString();
File file = new File(myImageStr);
try {
return Files.readBytes(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
};
}
};
chartImage.setOutputMarkupId(true);
chartImage.setOutputMarkupPlaceholderTag(true);
return chartImage;
}
This is where I use it
Image img = createImage("orig_photo", uploadedFile.getBytes());
pnlForm.addOrReplace(img);
My HTML
<img width="100" height="133" title="Photo" wicket:id="orig_photo"/>
Get this error:
Get this error in Javascript Inspect Element:
GET https://localhost/admin/admnwtxtprofile?5-IResourceListener-wProfileTxtPnl-wProfileTxtForm-orig_photo&antiCache=1439492929071 404 (Not Found)
You have imageData supplied to your createImage but then not used inside method.
I assume your uploadedFile is from some folder? May be temp?
The code below similar to yours' is working fine, showing the image.
public class WicketApplication extends WebApplication {
public static final String LOCAL_IMAGE_BASE = "c:\\myimages\\";
...
}
public class TestDynaImageFilePage extends WebPage {
public TestDynaImageFilePage(PageParameters parameters) {
super(parameters);
Form<Void> form = new Form<Void>("imageForm");
form.setOutputMarkupId(true);
add(form);
addFormComponents(form);
}
private void addFormComponents(Form<Void> form) {
Path path = Paths.get("src/main/webapp/images/help.png");
try {
byte[] data = java.nio.file.Files.readAllBytes(path);
Image img = createImage("orig_photo", data);
form.addOrReplace(img);
} catch (IOException e) {
e.printStackTrace();
}
}
private Image createImage(final String id, final byte[] imageData) {
NonCachingImage chartImage = new NonCachingImage(id) {
private static final long serialVersionUID = 1L;
#Override
protected IResource getImageResource() {
return new DynamicImageResource() {
private static final long serialVersionUID = 1L;
#Override
protected byte[] getImageData(Attributes attributes) {
String myImageStr = new StringBuffer(
WicketApplication.LOCAL_IMAGE_BASE).
append("help.png").toString();
File file = new File(myImageStr);
try {
return Files.readBytes(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
};
}
};
chartImage.setOutputMarkupId(true);
chartImage.setOutputMarkupPlaceholderTag(true);
return chartImage;
}
}
HTML:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns:wicket>
<head>
</head>
<body>
<form wicket:id="imageForm">
<img width="100" height="133" title="Photo" wicket:id="orig_photo"/>
</form>
</body>
</html>
I think this may have something to do with how Wicket request/response life cycle. I have the same code in BeforeRender method and it works fine but when I copy it in OnSubmit, it doesn't work.
My solution was to refresh the page in OnSubmit instead of calling the above method.
I'm trying to simply make objects out of a Twitter stream I download from a user. I am using the information provided from https://github.com/Rockncoder/TwitterTutorial. Can someone help determine if this code actually works? Some of the classes are kind of sketchy, as in the Twitter.java class is just an ArrayList and it only has what's listed below in it.
Is my process correct? Any help is appreciated.
public class MainActivity extends ListActivity {
private ListActivity activity;
final static String ScreenName = "riddlemetombers";
final static String LOG_TAG = "rmt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity = this;
downloadTweets();
}
// download twitter timeline after first checking to see if there is a network connection
public void downloadTweets() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadTwitterTask().execute(ScreenName);
} else {
Log.v(LOG_TAG, "No network connection available.");
}
}
// Uses an AsyncTask to download a Twitter user's timeline
private class DownloadTwitterTask extends AsyncTask<String, Void, String> {
final String CONSUMER_KEY = (String) getResources().getString(R.string.api_key);
final String CONSUMER_SECRET = (String)getResources().getString(R.string.api_secret);
final static String TwitterTokenURL = "https://api.twitter.com/oauth2/token";
final static String TwitterStreamURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";
#Override
protected String doInBackground(String... screenNames) {
String result = null;
if (screenNames.length > 0) {
result = getTwitterStream(screenNames[0]);
}
return result;
}
// onPostExecute convert the JSON results into a Twitter object (which is an Array list of tweets
#Override
protected void onPostExecute(String result) {
Twitter twits = jsonToTwitter(result);
// lets write the results to the console as well
for (Tweet tweet : twits) {
Log.i(LOG_TAG, tweet.getText());
}
// send the tweets to the adapter for rendering
ArrayAdapter<Tweet> adapter = new ArrayAdapter<Tweet>(activity, R.layout.items, twits);
setListAdapter(adapter);
}
// converts a string of JSON data into a Twitter object
private Twitter jsonToTwitter(String result) {
Twitter twits = null;
if (result != null && result.length() > 0) {
try {
Gson gson = new Gson();
twits = gson.fromJson(result, Twitter.class);
if(twits==null){Log.d(LOG_TAG, "Twits null");}
else if(twits!=null) {Log.d(LOG_TAG, "Twits NOT null");}
} catch (IllegalStateException ex) {
// just eat the exception
}
}
return twits;
}
// convert a JSON authentication object into an Authenticated object
private Authenticated jsonToAuthenticated(String rawAuthorization) {
Authenticated auth = null;
if (rawAuthorization != null && rawAuthorization.length() > 0) {
try {
Gson gson = new Gson();
auth = gson.fromJson(rawAuthorization, Authenticated.class);
} catch (IllegalStateException ex) {
// just eat the exception
}
}
return auth;
}
private String getResponseBody(HttpRequestBase request) {
StringBuilder sb = new StringBuilder();
try {
DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
String reason = response.getStatusLine().getReasonPhrase();
if (statusCode == 200) {
HttpEntity entity = response.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);
}
} catch (UnsupportedEncodingException ex) {
} catch (ClientProtocolException ex1) {
} catch (IOException ex2) {
}
return sb.toString();
}
private String getTwitterStream(String screenName) {
String results = null;
// Step 1: Encode consumer key and secret
try {
// URL encode the consumer key and secret
String urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
String urlApiSecret = URLEncoder.encode(CONSUMER_SECRET, "UTF-8");
// Concatenate the encoded consumer key, a colon character, and the
// encoded consumer secret
String combined = urlApiKey + ":" + urlApiSecret;
// Base64 encode the string
String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);
// Step 2: Obtain a bearer token
HttpPost httpPost = new HttpPost(TwitterTokenURL);
httpPost.setHeader("Authorization", "Basic " + base64Encoded);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
String rawAuthorization = getResponseBody(httpPost);
Authenticated auth = jsonToAuthenticated(rawAuthorization);
// Applications should verify that the value associated with the
// token_type key of the returned object is bearer
if (auth != null && auth.token_type.equals("bearer")) {
// Step 3: Authenticate API requests with bearer token
HttpGet httpGet = new HttpGet(TwitterStreamURL + screenName);
// construct a normal HTTPS request and include an Authorization
// header with the value of Bearer <>
httpGet.setHeader("Authorization", "Bearer " + auth.access_token);
httpGet.setHeader("Content-Type", "application/json");
// update the results with the body of the response
results = getResponseBody(httpGet);
}
} catch (UnsupportedEncodingException ex) {
} catch (IllegalStateException ex1) {
}
return results;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
TWITTER CLASS
import java.util.ArrayList;
// a collection of tweets
public class Twitter extends ArrayList<Tweet> {
private static final long serialVersionUID = 1L;
}
TWEET CLASS
import com.google.gson.annotations.SerializedName;
public class Tweet {
#SerializedName("created_at")
private String DateCreated;
#SerializedName("id")
private String Id;
#SerializedName("text")
private String Text;
#SerializedName("in_reply_to_status_id")
private String InReplyToStatusId;
#SerializedName("in_reply_to_user_id")
private String InReplyToUserId;
#SerializedName("in_reply_to_screen_name")
private String InReplyToScreenName;
#SerializedName("user")
private TwitterUser User;
public String getDateCreated() {
return DateCreated;
}
public String getId() {
return Id;
}
public String getInReplyToScreenName() {
return InReplyToScreenName;
}
public String getInReplyToStatusId() {
return InReplyToStatusId;
}
public String getInReplyToUserId() {
return InReplyToUserId;
}
public String getText() {
return Text;
}
public void setDateCreated(String dateCreated) {
DateCreated = dateCreated;
}
public void setId(String id) {
Id = id;
}
public void setInReplyToScreenName(String inReplyToScreenName) {
InReplyToScreenName = inReplyToScreenName;
}
public void setInReplyToStatusId(String inReplyToStatusId) {
InReplyToStatusId = inReplyToStatusId;
}
public void setInReplyToUserId(String inReplyToUserId) {
InReplyToUserId = inReplyToUserId;
}
public void setText(String text) {
Text = text;
}
public void setUser(TwitterUser user) {
User = user;
}
public TwitterUser getUser() {
return User;
}
#Override
public String toString(){
return getText();
}
}
I've done several Log.d(LOG_TAG, Stuff) to see if I'm getting stuff, and it indicates I'm getting some kind of content back. Maybe the problem is in making objects of the data.
Not sure why you want to use the code from https://github.com/Rockncoder/TwitterTutorial.
Why don't use use http://twitter4j.org. They have give sample example to use it.
Moreover it support Twitter 1.1 as well. Just include twitter-core.jar and you are ready write your code.
Hope it helps.