Google Form fill from Java - java

I need to fill basic Google Form from my Java code but it throws org.apache.http.client.ClientProtocolException: Unexpected response status: 405
Here is my code :
private boolean sendMessage(UserInfo userInfo) {
final HttpPost req = new HttpPost("my-form-url");
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
List<NameValuePair> form = new ArrayList<>();
form.add(new BasicNameValuePair("entry.1301726507", userInfo.getName()));
form.add(new BasicNameValuePair("entry.1466759457", "hello"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(form, Consts.UTF_8);
req.setEntity(entity);
System.out.println("Executing request " + req.getRequestLine());
ResponseHandler<String> responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity responseEntity = response.getEntity();
return responseEntity != null ? EntityUtils.toString(responseEntity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
String responseBody = httpclient.execute(req, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
And here is the form :
what am I doing wrong?

You may use my pet project to do the job for you:
Add dependency:
<dependency>
<groupId>io.github.stepio.jgforms</groupId>
<artifactId>jgforms</artifactId>
<version>1.0.1</version>
</dependency>
Define your form:
public enum MyForm implements MetaData {
USER_NAME(1301726507L),
MESSAGE(1466759457L);
private long id;
JGForm(long id) {
this.id = id;
}
#Override
public long getId() {
return this.id;
}
}
Fill the form and submit:
private boolean sendMessage(UserInfo userInfo) {
URL url = Builder.formKey("my-form-key-from-url")
.put(MyForm.USER_NAME, userInfo.getName())
.put(MyForm.MESSAGE, "hello")
.toUrl();
Submitter submitter = new Submitter(
new Configuration()
);
try {
submitter.submitForm(url);
} catch (NotSubmittedException ex) {
// TODO: log & handle the exception properly
return false;
}
return true;
}
Check README and unit tests for more details and examples:
https://github.com/stepio/jgforms

Related

Implement CustomFeignLogger for feign interface

I have this interface:
#FeignClient(name = "${test.feign.name}", url = "${test.feign.url}", configuration = TestConfiguration.class)
public interface TestFeignClient {
#GetMapping(value = "/users", produces = "application/json")
ResponseEntity<?> getAll();
}
And I want to track the log by creating this class CustomFeignLogger.
This CustomFeignLogger object should extends Slf4jLogger Object and override this method:
protected Response logAndRebufferResponse(String configKey,
Level logLevel,
Response response,
long elapsedTime)
throws IOException {
if (logger.isDebugEnabled()) {
return super.logAndRebufferResponse(configKey, logLevel, response, elapsedTime);
}
return response;
}
In the TestConfiguration class you need to inject new bean CustomFeignLogger
#AllArgsConstructor
public class TestConfiguration {
#Bean
public CustomFeignLogger feignLogger() {
return new CustomFeignLogger();
}
}
Then you need to override logAndRebufferResponse method tike this:
protected Response logAndRebufferResponse(String configKey, Logger.Level logLevel, Response response, long elapsedTime) throws IOException {
String responseBody = null;
String reason = response.reason() != null && logLevel.compareTo(Logger.Level.NONE) > 0 ? " " + response.reason() : "";
int status = response.status();
this.log(configKey, "<--- HTTP/1.1 %s%s (%sms)", status, reason, elapsedTime);
// ---------------- Logging headers ----------------
Iterator headersIterator = response.headers().keySet().iterator();
while(headersIterator.hasNext()) {
String field = (String) headersIterator.next();
Iterator valuesIterator = Util.valuesOrEmpty(response.headers(), field).iterator();
while(valuesIterator.hasNext()) {
String value = (String)valuesIterator.next();
this.log(configKey, "%s: %s", field, value);
}
}
// -------------------------------------------------
//----------------- Logging response body ---------------
int bodyLength = 0;
if (response.body() != null
&& status != HttpStatus.SC_NO_CONTENT
&& status != HttpStatus.SC_RESET_CONTENT) {
this.log(configKey, "");
byte[] bodyData = Util.toByteArray(response.body().asInputStream());
bodyLength = bodyData.length;
if (bodyLength > 0) {
String body = Util.decodeOrDefault(bodyData, Util.UTF_8, "Binary data");
responseBody = body.toString();
this.log(configKey, "%s", body);
}
this.log(configKey, "<--- END HTTP ttttt (%s-byte body)", bodyLength);
// trackingService.track
return response.toBuilder().body(bodyData).build();
}
this.log(configKey, "<--- END HTTP tttt (%s-byte body)", Integer.valueOf(bodyLength));
// -------------------------------------------------
return response;
}

Request is not send without block()

I want to use this webflux client code to send POST requests with reply and without reply. I tried this code implementation:
public class RestClientBuilder {
private String token;
private String username;
private String password;
private URL gatewayUrl;
private SslContextBuilder sslContextBuilder;
public static RestClientBuilder builder() {
return new RestClientBuilder();
}
public RestClientBuilder token(String token) {
this.token = validateAndTrim(token, "Token");
return this;
}
public RestClientBuilder usernamePassword(String username, String password) {
this.username = validateAndTrim(username, "Username");
this.password = validateAndTrim(password, "Password");
return this;
}
private String validateAndTrim(String value, final String parameter) {
if (value == null || value.trim().isEmpty()) {
throw new IllegalArgumentException(parameter + " is empty");
}
return value.trim();
}
public RestClientBuilder gatewayUrl(String gatewayUrl) {
String urlSt = validateAndTrim(gatewayUrl, "Gateway URL");
try {
this.gatewayUrl = new URL(urlSt);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Malformed URL: " + urlSt, e);
}
return this;
}
public RestClientBuilder truststore(File truststoreFile) {
getSslContextBuilder().trustManager(truststoreFile);
return this;
}
public RestClientBuilder sslCertificate(File keyCertChainFile, File keyFile, String keyPassword) {
getSslContextBuilder().keyManager(keyCertChainFile, keyFile, keyPassword);
return this;
}
public RestClient build() throws SSLException {
SslContext sslContext = sslContextBuilder != null ? sslContextBuilder.build() : null;
return new RestClient(gatewayUrl.toString(), token, username, password, sslContext);
}
private SslContextBuilder getSslContextBuilder() {
if (sslContextBuilder == null) {
sslContextBuilder = SslContextBuilder.forClient();
}
return sslContextBuilder;
}
}
Implementation of the rest client:
public class RestClient {
private WebClient client;
private String gatewayUrl;
public RestClient(String gatewayUrl, String token, String username, String password, SslContext sslContext) {
this.gatewayUrl = gatewayUrl;
WebClient.Builder builder = WebClient.builder().baseUrl(gatewayUrl);
if (sslContext != null) {
HttpClient httpClient = HttpClient.create().secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
ClientHttpConnector httpConnector = new ReactorClientHttpConnector(httpClient);
builder.clientConnector(httpConnector);
}
if (username != null && password != null) {
builder.filter(basicAuthentication(username, password));
}
client = builder.build();
}
public Mono<Void> executeOnly(ReportRequest transaction) {
Mono<ReportRequest> transactionMono = Mono.just(transaction);
return client.post().uri(gatewayUrl)
.accept(MediaType.APPLICATION_XML)
.contentType(MediaType.APPLICATION_XML)
.body(transactionMono, ReportRequest.class)
.retrieve()
.bodyToMono(Void.class);
}
}
Make remote calls:
public class ReportingProcessor {
private String URL2 = "......";
public void collectEnvironmentData() throws JAXBException {
ReportRequest report = new ReportRequest();
report.setVersion("1.0");
RestClient client = null;
try {
client = RestClientBuilder.builder()
.gatewayUrl(URL2)
// .token(contract.getTerminal_token())
// .usernamePassword("user", "password")
// .truststore(new File("server.pem"))
// .sslCertificate(new File("client.pem"), new File("clientKey.p8"), "secret")
.build();
} catch (SSLException e) {
e.printStackTrace();
}
Mono<Void> result = client.executeOnly(report);
Void response = result.block();
}
When I remove Void response = result.block(); the request is not send. I Can't find why. Can you give me some advice how to make the client code working without using block().
Whenever you work with Spring-webflux you have to keep one thing in mind. i.e You don't have to break your chain. because it is necessary to, someone should call subscribe on your chain. as it works on RXJava specification.
if you break the chain then you have to call block() which not recommended.
you have to modify your code in the below manner.
Let's Consider you have a handler which is making a call to your collectEnvironmentData() method and your method is making a call to remote service.
public Mono<ServerResponse> handelerMethod(ServerRequest request){
return collectEnvironmentData().flatMap(aVoid -> ServerResponse.ok().build());
}
your method should be modified to
public Mono<Void> collectEnvironmentData() throws JAXBException {
ReportRequest report = new ReportRequest();
report.setVersion("1.0");
RestClient client = null;
try {
client = RestClientBuilder.builder()
.gatewayUrl(URL2)
// .token(contract.getTerminal_token())
// .usernamePassword("user", "password")
// .truststore(new File("server.pem"))
// .sslCertificate(new File("client.pem"), new File("clientKey.p8"),
//"secret").build();
} catch (SSLException e) {
e.printStackTrace();
}
return client.executeOnly(report);
}
Change your implementation in the above manner, hope it will work.
How I would implement your method is:
public Mono<Void> executeOnly(ReportRequest transaction) {
Mono<ReportRequest> transactionMono = Mono.just(transaction);
return client.post().uri(gatewayUrl)
.accept(MediaType.APPLICATION_XML)
.contentType(MediaType.APPLICATION_XML)
.body(transaction, ReportRequest.class)
.exchange()
.then();
}
And then I would use it as follows:
client.executeOnly(report).subscribe()
Change the method return type to Mono<Void> for end to end streaming.
public void collectEnvironmentData() throws JAXBException {
ReportRequest report = new ReportRequest();
report.setVersion("1.0");
RestClient client = null;
try {
client = RestClientBuilder.builder()
.gatewayUrl(URL2)
.build();
} catch (SSLException e) {
e.printStackTrace();
}
return client.executeOnly(report);
}
Or you can also subscribe the Mono
client.executeOnly(report).subscribe();

Not able to typecast from String to a class in Spring REST

Getting following exception while hitting a Rest endpoint. How do I typecast from String to ProtectPanReplyType class?
Error:
Error - Request: http://localhost:9090/hosted-payments-webapp-1.0.0/pan/protect
raised java.lang.ClassCastException: com.gsicommerce.api.checkout.ProtectPanReplyType cannot be cast to java.lang.String
ProtectPanServiceImpl.java
#Service
public class ProtectPanServiceImpl implements ProtectPanService {
#Override
public ResponseEntity<?> sendProtectPanRequest(ProtectPan protectPan) {
String pan = protectPan.getPaymentAccountNumber();
String tenderClass = protectPan.getTenderClass();
String protectPanRequest = XMLHelper.createProtectPanRequest(pan, tenderClass);
System.out.println("protectPanRequest = " + protectPanRequest);
ResponseEntity<String> response = null;
try {
response = ApiClientUtils.callClientByEndpointandMessage(protectPanRequest, DEV_PUBLIC_API_URL,
ProtectPanReplyType.class);
System.out.println("response.getClass() = " + response.getClass());
//DOES NOT WORK
//ProtectPanReplyType protectPanReplyType = (ProtectPanReplyType)response.getBody();
//THROWS ClassCastException HERE
System.out.println(response.getBody());
} catch (JiBXException e) {
e.printStackTrace();
}
return response;
}
}
ApiClientUtils.java
public ResponseEntity<String> callClientByEndpointandMessage(String xmlRequest, String endpoint, Class<?> replyType) throws JiBXException {
HttpEntity<String> request = createRequestForUser("username", "secret",xmlRequest);
ResponseEntity<String> response = restOperations.postForEntity(endpoint, request, String.class);
ResponseEntity formattedResponse = new ResponseEntity(null, HttpStatus.BAD_REQUEST);
try {
Object jibxObject = JibxHelper.unmarshalMessage(response.getBody(), replyType);
formattedResponse = new ResponseEntity(jibxObject, HttpStatus.OK);
} catch (JiBXException e) {
FaultResponseType faultResponse = JibxHelper.unmarshalMessage(response.getBody(), FaultResponseType.class);
formattedResponse = new ResponseEntity(faultResponse, HttpStatus.BAD_REQUEST);
}
return formattedResponse;
}
ProtectPan.java
public class ProtectPan {
#JsonProperty("paymentAccountNumber")
private String paymentAccountNumber;
#JsonProperty("tenderClass")
private String tenderClass;
public String getPaymentAccountNumber() {
return paymentAccountNumber;
}
public String getTenderClass() {
return tenderClass;
}
}
ProtectPanReplyType.java
public class ProtectPanReplyType {
private String token;
private List<Element> anyList = new ArrayList<Element>();
private String sessionId;
//getters and setter removed for brevity
}
Use ResponseEntity<ProtectPanReplyType> instead ResponseEntity<String>
Build and Return ProtectPanReplyType from your restOperations.postForEntity()
Was finally able to get the object after making following changes.
ApiClientUtils.java
public ResponseEntity<?> callClientByEndpointandMessage(String xmlRequest, String endpoint, Class<?> replyType) throws JiBXException {
HttpEntity<String> request = createRequestForUser("payment", "SONitc2m8y", xmlRequest);
ResponseEntity<String> response = restOperations.postForEntity(endpoint, request, String.class);
ResponseEntity<?> formattedResponse = null;
try {
Object jibxObject = JibxHelper.unmarshalMessage(response.getBody(), replyType);
formattedResponse = new ResponseEntity(jibxObject, HttpStatus.OK);
} catch (JiBXException e) {
FaultResponseType faultResponse = JibxHelper.unmarshalMessage(response.getBody(), FaultResponseType.class);
formattedResponse = new ResponseEntity(faultResponse, HttpStatus.BAD_REQUEST);
}
return formattedResponse;
}
ProtectPanServiceImpl.java
#Override
public ResponseEntity<?> sendProtectPanRequest(ProtectPan protectPan) {
String pan = protectPan.getPaymentAccountNumber();
String tenderClass = protectPan.getTenderClass();
String protectPanRequest = XMLHelper.createProtectPanRequest(pan, tenderClass);
ResponseEntity<?> response = null;
try {
response = publicApiClientUtils.callClientByEndpointandMessage(protectPanRequest, DEV_PUBLIC_API_URL, ProtectPanReplyType.class);
ProtectPanReplyType protectPanReplyType = (ProtectPanReplyType) response.getBody();
System.out.println("protectPanReplyType = " + protectPanReplyType);
} catch (JiBXException e) {
e.printStackTrace();
}
return response;
}

Parallelstream.ForEach() double item

I have a piece of software that generates SOAP-requests based on an excel-file, and then emails the results.
Due to the potential size of the requests, I do the soap-request-handling in parallel. The following code handles the above mentioned.
public void HandleData() {
List<NodeAnalysisReply> replies = Collections.synchronizedList(new ArrayList<>());
new Thread(() -> {
List<NodeAnalysisRequest> requests;
SOAPMessageFactory factory = new SOAPMessageFactory();
SOAPResponseParser parser = new SOAPResponseParser();
try {
requests = new ExcelParser().parseData(file);
requests.parallelStream().forEach((request) -> {
try {
SOAPMessage message = factory.createNodeRequestMessage(
new RequestObject(requestInfoFactory.makeInfo(trackingID), request));
SOAPMessage response = new SoapConnector(server.getUrl()).executeRequest(message);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.writeTo(out);
NodeAnalysisReply curReply = parser.ParseXMLResponse(out.toString(), request);
synchronized (replies) {
System.out.println("Adding: " + curReply.getRequest().toString());
replies.add(curReply);
}
} catch (UnsupportedOperationException | SOAPException | IOException e) {
handleSoap(e.getMessage());
}
});
} catch (IOException e) {
handleBadParse();
}
try {
for(NodeAnalysisReply reply : replies){
System.out.println("Data: " + reply.getRequest().toString());
}
mailer.SendEmail("Done", email, replies);
} catch (MessagingException e) {
e.printStackTrace();
}
}).start();
}
When I run the code with two piece of data, the following happens:
Adding: Søndergade 52 6920 // OK
Adding: Ternevej 1 6920 // OK
Data: Ternevej 1 6920 // What
Data: Ternevej 1 6920 // WHAT..
are equal? true
So even though it adds both items to the list, it seems like the last one takes both places. How come is that, and how do I solve it? - I really do miss the Parrallel.ForEach() form C#!
EDIT: As requested, the code for NodeAnalysisReply.
public class NodeAnalysisReply {
public ReplyInfo getReplyInfo() {
return replyInfo;
}
public void setReplyInfo(ReplyInfo replyInfo) {
this.replyInfo = replyInfo;
}
public List < nodeAnalysisListDetails > getNodeAnalysisListDetails() {
return nodeAnalysisListDetails;
}
public void setNodeAnalysisListDetails(List < nodeAnalysisListDetails > nodeAnalysisListDetails) {
this.nodeAnalysisListDetails = nodeAnalysisListDetails;
}
public void addNodeAnalysisListDetail(nodeAnalysisListDetails nodeAnalysisListDetails) {
this.nodeAnalysisListDetails.add(nodeAnalysisListDetails);
}
ReplyInfo replyInfo;
public String getFormattedXML() {
return formattedXML;
}
public void setFormattedXML(String formattedXML) {
this.formattedXML = formattedXML;
}
String formattedXML;
public NodeAnalysisRequest getRequest() {
return request;
}
public void setRequest(NodeAnalysisRequest request) {
this.request = request;
}
NodeAnalysisRequest request;
List < nodeAnalysisListDetails > nodeAnalysisListDetails = new ArrayList < > ();
}
synchronized (replies) {
System.out.println("Adding: " + curReply.getRequest().toString());
replies.add(curReply);
}
The above code in a lambda of stream is called a side effect and is not encouraged at all.
What you should do is something like below.
replies.addAll(requests.parallelStream().map((request) -> {
try {
SOAPMessage message = factory.createNodeRequestMessage(
new RequestObject(requestInfoFactory.makeInfo(trackingID), request));
SOAPMessage response = new SoapConnector(server.getUrl()).executeRequest(message);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.writeTo(out);
NodeAnalysisReply curReply = parser.ParseXMLResponse(out.toString(), request);
return curReply;
} catch (UnsupportedOperationException | SOAPException | IOException e) {
handleSoap(e.getMessage());
return null;
}
})
.filter(curReply -> curReply != null)
.collect(Collectors.toList())
);
In the Above code you map each request to a NodeAnalysisReply first and then filter only the non null values and finally you Collect it into a list and all those to your replies list.

Android Twitter App Can't Make Objects from Json Response

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.

Categories

Resources