Flutter Jaguar HTTP cookie - dart

I am using jaguar http library to perform network queries.
I am trying to get a cookie which should be returned from an http request.
I would like to save the cookie and send it on later queries.
Can anyone help with this?

I've figure it out!
you can use their interceptors to get the cookies from the response and add them to requests:
Here is a suggestion of how your api class can manage cookies.
import 'package:jaguar_retrofit/jaguar_retrofit.dart';
import 'package:jaguar_serializer/src/repo/repo.dart';
import 'package:jaguar_resty/jaguar_resty.dart' as resty;
import 'package:jaguar_resty/jaguar_resty.dart';
import 'package:http/http.dart';
import 'package:client_cookie/client_cookie.dart';
#GenApiClient(path: "apiPath")
class MyApi extends _$MyApiClient implements ApiClient{
#override
resty.Route base;
#override
SerializerRepo serializers;
MyApi({this.base, this.serializers}){ //Prepare the API in its constructor
globalClient = IOClient();
List<ClientCookie> cookies = List<ClientCookie>(); //Prepare alist of cookies
this.base.after((resty.StringResponse response){
Map map = response.headers.map((key, value){
return MapEntry(key, value);
});
String cookieStr = map["set-cookie"]; //Extract cookies from response header
print("Cookies Str: $cookieStr");
if(cookieStr != null){
cookies.clear();
cookies.addAll(Utils.cookies(cookieStr)); //Build your cookies and add them to the list
}
}
);
this.base.before((base1){ //This is 'before 'interceptor
base1.cookies(cookies); //add the cookies list to queries here
}
);
}//ApiConstructor
#GetReq(path: "something")
Future<dynamic> getSomething();
}

Related

Send Template Email Using Struts2 View

I am using Struts2, and I want to send the html output of one of my actions as an email.
In other words, instead of displaying the output html in the browser, I want to send it as an email.
I am using Apache Tiles to create my pages.
EDIT:
In general, can we get the the html result of struts view as a stream and pass it to another action?
First of all, I need to mention that using JSPs as email templates are not a good idea. But, if you need to do this, or you need to log the exact HTML that user sees (or any other reason), you can do this:
Create an interceptor for your action
Get the response from ServletActionContext
Wrap the response
Invoke the action
get (or even change) the response.
return the result.
This is part of my code:
import java.io.CharArrayWriter;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
//STEP 1
public class EmailInterceptor implements Interceptor {
#Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
// STEP 2
HttpServletResponse response = ServletActionContext.getResponse();
PrintWriter out = response.getWriter();
// STEP 3
CharResponseWrapper responseWrapper = new CharResponseWrapper((HttpServletResponse) response);
ServletActionContext.setResponse(responseWrapper);
// STEP 4
String result = actionInvocation.invoke();
// STEP 5
String servletResponse = new String(responseWrapper.toString());
out.write(servletResponse + "whatever");
// STEP 6
return result;
}
public class CharResponseWrapper extends HttpServletResponseWrapper {
private CharArrayWriter output;
public String toString() {
return output.toString();
}
public CharResponseWrapper(HttpServletResponse response) {
super(response);
output = new CharArrayWriter();
}
public PrintWriter getWriter() {
return new PrintWriter(output);
}
}
}

how to get the user's timeline of one's own twitter account through twitter api in java

I had been trying to get my timeline messages through some Java code explained in the http://www.dreamincode.net/forums/blog/114/entry-4459-demo-of-twitter-application-only-oauth-authentication-using-java blog and wrote some code in Java.
I am using application-only authentication and using consumer key and consumer secret. Here is a portion of my code where I am requesting the bearer token:
bearerToken=requestBearerToken("https://api.twitter.com/1.1/statuses/besra_u_timeline.json");
Is this the right way? I ask because in the requestBearerToken method
private static String requestBearerToken(String endPointUrl) throws IOException {
HttpsURLConnection connection = null;
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
try {
connection.getInputStream();
} catch(IOException e){
System.out.println("IOException");
}
I am constantly getting an IOException which means that I am not getting the input stream from the connection object. Please help me to get the tweets.
Ya i have got a way to do it using the twitter4j api.Consumer key , consumer secret, access token and access secret u can get once u register ur app in dev.twitter.com/apps
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.Status;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
public class SimpleCrawler {
static ResponseList<Status> statuses;
public static void main(String[] args) throws TwitterException {
ConfigurationBuilder cb=new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("your consumer key")
.setOAuthConsumerSecret("your con secret")
.setOAuthAccessToken("your access token")
.setOAuthAccessTokenSecret("access token secret");
TwitterFactory tf=new TwitterFactory(cb.build());
Twitter tw = tf.getInstance();
try {
statuses=tw.getHomeTimeline();
System.out.println("Connected to twitter");
} catch (TwitterException e) {
System.out.println("Cannot connect to Twitter");
System.exit(0);
}
System.out.println("Reading TimeLine...");
for(Status st1:statuses){
String data[]={st1.getUser().getName(),String.valueOf(st1.getCreatedAt()),twtmsg};
System.out.println(data);
}
}
}
Through twitter api also its possible but don't know . One problem with this method is that it fetches 20 tweets only at a time ,any help would be appreciated.suggestions are most welcome plz comment.
You need to use Paging:
Paging paging = new Paging();
paging.setPage(1);
ResponseList<Status> statuses = twitter.getHomeTimeline(paging);
System.out.println(statuses.size());
paging.setPage(2);
statuses.addAll(twitter.getHomeTimeline(paging));
System.out.println(statuses.size());
The above simplified code will give you two pages worth of statuses

Retrieving the response body from an HttpClientResponse

I'm trying to write some tests for my Dart server application, and I've been using the HttpClient class (along with the related HttpClientRequest and HttpClientResponse classes to make test requests to the server (note that I'm using these classes because I need the dart:io package for running the server, so I can't also import dart:html). This has been going fairly well so far, and I've been able to write tests to check that the server is returning responses with the correct HTTP Status code. The base of the code I've been using to make these test calls is as follows:
Future<HttpClientResponse> makeServerRequest(String method, Uri uri, [String jsonData]) async {
HttpClient client = new HttpClient();
HttpClientRequest request = await client.openUrl(method, uri);
request.write(jsonData);
return request.close();
}
Now I need to write a test that makes sure that the body of the response, not just the status code, is correct. The problem is that I can't seem to find anything that allows me to actually access the response body in the HttpClient* classes. The closest I've been able to find so far is the HttpClientResponse.contentLength property, but that only tells me how big the response body is, and isn't the actual content.
How do I retrieve the response body from these requests? Or, if you aren't able to, is there some other way I can make the requests on a server side application so I can read the responses?
The HttpClientResponse object is a Stream, so you can just read it with the listen() method:
response.listen((List<int> data) {
//data as bytes
});
You can also use the codecs from dart:convert to parse the data. The following example reads the response contents to a String:
import 'dart:io';
import 'dart:convert';
import 'dart:async';
Future<String> readResponse(HttpClientResponse response) {
final completer = Completer<String>();
final contents = StringBuffer();
response.transform(utf8.decoder).listen((data) {
contents.write(data);
}, onDone: () => completer.complete(contents.toString()));
return completer.future;
}
Low level
Here is the await for version of collecting the response stream. It's a little more compact than using a completer.
Future<String> readResponse(HttpClientResponse response) async {
final contents = StringBuffer();
await for (var data in response.transform(utf8.decoder)) {
contents.write(data);
}
return contents.toString();
}
You should wrap it in a try catch block to handle errors.
High level
Most of the time from the client side you would use the http library instead:
// import 'package:http/http.dart';
Response response = await get(url);
String content = response.body;
See this article for more details.
A short way of getting the body from an HttpClientResponse is:
Future<String> readResponse(HttpClientResponse response) async {
return response.transform(utf8.decoder).join();
}

How to authenticate with Twitter API 1.1 and Scribe?

I'm trying to pull a timeline from my own twitter account in to a website using Scribe. I tried the provided Twitter example, but I'm always getting the following response from twitter:
{"errors":[{"message":"Could not authenticate you","code":32}]}
I tried this by using my own access token as well as a dynamically created one.
Code for using my own access token:
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.TwitterApi;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;
public class TwitterTest {
public static void main(String[] args) {
OAuthService service = new ServiceBuilder()
.provider(TwitterApi.SSL.class)
.apiKey("myApiKey")
.apiSecret("myApiSecret")
.build();
Token accessToken = new Token("myAccessToken", "myAccessTokenSecret");
OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.twitter.com/1.1/statuses/user_timeline.json");
service.signRequest(accessToken, request);
Response response = request.send();
System.out.println(response.getBody());
}
}

how to simply fetch an url body as a string synchronously

How would you simply implement this function:
String fetchUrlBodyAsString(String url) {
...
}
Usage:
String schema = fetchUrlBodyAsString("http://json-schema.org/draft-04/schema#");
This thread Using dart to download a file explains a good way to get to the data from a main function. But if you try it you see that the real work happens after leaving main. I think that the synchronous function that I want to create is difficult using HttpClient because it is trying to get an async api to work synchronously. According to this thread that may not be possible: https://groups.google.com/a/dartlang.org/d/msg/misc/kAgayQyaPhQ/wonJ776_FGIJ
What is a Dart way to implement this in a non-browser/console setting?
The using of asynchronous methods is really infectious. Once you start using Future inside a function you have to return a Future as result. So your fetchUrlBodyAsString function can look like :
import 'dart:io';
import 'dart:async';
Future<String> fetchUrlBodyAsString(String url) =>
new HttpClient().getUrl(Uri.parse(url))
.then((HttpClientRequest request) => request.close())
.then((HttpClientResponse response) =>
response.transform(new StringDecoder()).join());
main() {
final url = "http://json-schema.org/draft-04/schema#";
Future<String> schema = fetchUrlBodyAsString(url);
schema.then(handleContent);
}
handleContent(String content) {
print(content); // or do what you want with content.
}
or with async/await:
import 'dart:io';
import 'dart:async';
Future<String> fetchUrlBodyAsString(String url) async {
var request = await new HttpClient().getUrl(Uri.parse(url));
var response = await request.close();
return response.transform(new StringDecoder()).join();
}
main() async {
final url = "http://json-schema.org/draft-04/schema#";
handleContent(await fetchUrlBodyAsString(url));
}
handleContent(String content) {
print(content); // or do what you want with content.
}
You can make synchronous http requests by using HttpRequest.open and setting async to false.
https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-dom-html.HttpRequest#id_open
import 'dart:html';
String fetchUrlBodyAsString(String url) {
var request = new HttpRequest()
..open('GET', url, async: false)
..send();
return request.responseText;
}
String schema = fetchUrlBodyAsString("http://json-schema.org/draft-04/schema#");
There is no way to turn an async API into a sync API; once you have a Future as a result, that is what you will have to deal with.
For your specific example, the only way to achieve what you want would be to build your own synchronous HTTP library from the ground up. Using asynchronous APIs in a synchronous manner is not possible.

Resources