When I do a request for a profile picture, mine in this case I receive some kind of encoded string in my HttpResponseHandler. The code below is the request for my profile picture.
private static AsyncHttpClient client = new AsyncHttpClient();
client.get("http://graph.facebook.com/1206433/picture", fbPictureHandler);
The code below is my handler to retrieve a response. I get the response as a string, but I am not sure what to do with this response object. I have tried converting to a byte array and writing to "file.jpg" this hasnt worked. My main question is what do I do with this response object?
private static AsyncHttpResponseHandler fbPictureHandler = new AsyncHttpResponseHandler ()
{
#Override
public void onStart() {
Log.d(TAG,"started picture handler");
}
#Override
public void onSuccess(String response) {
//Not sure what to do here, have been unable to do anything with this Byte //array
byte[] imageBackground = response.getBytes();
}
#Override
public void onFailure(Throwable error) {
Log.d(TAG, "unable to retrieve picture");
error.printStackTrace();
}
#Override
public void onFinish() {
Log.d(TAG,"Finished picture handler");
}
};
This is the PrintString of the response object
11-29 19:42:12.640: D/Yatter Facebook(3551): ÿØÿà��JFIF������������ÿþ��;CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 95
ANy help is greatly appreciated and hopefully this can help others.
Thank you,
Use the following request instead of the one that you are issuing
http://graph.facebook.com/1206433?fields=picture
This will return a JSON string to you in the following format which contains the original path to the profile image.
{
"picture": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/260615_1206433_140418666_q.jpg"
}
Parse this string to get the path of "picture" and use it in your code to get the picture.
Here is a sample request example
NOTE : http://profile.ak.fbcdn.net/hprofile-ak-snc4/260615_1206433_140418666_q.jpg is obtained by parsing the JSON string in the first step.
WebRequest request = WebRequest.Create("http://profile.ak.fbcdn.net/hprofile-ak-snc4/260615_1206433_140418666_q.jpg");
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
pictureBox1.Image = Image.FromStream(stream);
This will load the image to a picture box in a windows form application.
If you need anymore help let me know.
you can use ?redirect=false follow '/picture' for get direct link
http://graph.facebook.com/+facebookid+/picture?redirect=false
and response contain url static link (json format)
{"data":{
"url":"https:\/\/fbcdn-profile-a.akamaihd.net\/hprofile-ak-frc1\/t1.0-1\/c126.33.409.409\/s50x50\/551571_4079894629426_190963543_n.jpg","is_silhouette":false}
}
Related
I know how to create a plain link to download arbitrary binary data (using ResourceLink with ResourceStreamResource and AbstractResourceStream), but now I want to create a form whose submit button should either redirect to the form again (e.g. to correct an input error) or to download an arbitrary binary data file without going to a different page. How this can be achieved?
For the binary part, try something like this:
final ResourceStreamRequestHandler target = new ResourceStreamRequestHandler(new AbstractResourceStream() {
#Override
public String getContentType() {
return "application/octet-stream";
}
#Override
public InputStream getInputStream() throws ResourceStreamNotFoundException {
return new ByteArrayInputStream(yourBinaryContent);
}
#Override
public void close() throws IOException {
}
});
target.setFileName("response.dat");
target.setContentDisposition(ContentDisposition.ATTACHMENT);
getRequestCycle().scheduleRequestHandlerAfterCurrent(target);
Otherwise, to handle 'text' responses, use the code you already have.
I am trying to upload an image to Google Drive using Google Picker user interface. So far i have been unsuccessful.
This is the code that i am using :
private void onCreatePicker(ViewId viewId) {
final Picker picker = PickerBuilder.create()
.setTitle("Subir imagen a Google Drive")
.addView(viewId)
.addView(DocsUploadView())
.setLocale("es")
.setOAuthToken(token_oauth2)
.setDeveloperKey(DEVELOPER_KEY)
.setCallback(buildPickerCallback(viewId))
.build();
picker.setVisible(true);
}
private JavaScriptObject DocsUploadView() {
return com.ip.gae.gartla.shared.DocsUploadView.create();
}
I request your help on what could i be missing.
Thank you for your time,
Regards,
UPDATE: It seems that my application scope was wrong. In order to generate the correct oAuth2Token, you must declare the scope which you want to generate the token for:
The following its the method I am using to generate the token:
private void tokenOauth2() {
AuthRequest req = new AuthRequest(AUTH_URL, CLIENT_ID)
.withScopes(GOOGLE_DRIVE_SCOPE); // Can specify multiple scopes here
Auth.get().login(req, new Callback<String, Throwable>() {
#Override
public void onSuccess(String token) {
token_oauth2 = token;
}
#Override
public void onFailure(Throwable caught) {
// The authentication process failed for some reason, see caught.getMessage()
}
});
}
And here it is the GOOGLE_DRIVE_SCOPE variable that i am using:
String GOOGLE_DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
So, for now this is working for me. I have attached the solution so if someone finds it out interesting enough. :-)
I need little help to achieve this, in my app user can upload files to server and its stored as blob object, and now i need to show them to user up on there request.
What I am up to is show in below code,
On server side I put content to response:
(This code is implemented based on this blog post WaterTalks)
resp.setContentType("text/plain");
resp.setHeader("Content-Disposition", "attachment; filename=output.txt");
PrintWriter out = resp.getWriter();
out.println("This is the output content");
out.println("Probably something dynamic should go in here:::::");
PersistenceManager pm = null;
try {
pm = PMF.get().getPersistenceManager();
javax.jdo.Transaction transaction = pm.currentTransaction();
Extent e = pm.getExtent(WaterTalkFiles.class, true);
Iterator iter = e.iterator();
String returns = "";
WaterTalkFiles file = (WaterTalkFiles)iter.next();
Blob blob = file.getData();
byte[] buffer = blob.getBytes();
String s = new String(buffer);
out.println(s);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != pm)
pm.close();
}
Now in client side when user click show button i want to show the file content in browser, not to download it.
My client side code is:
showfilecontentButton.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
String link = "/FileUploadByWaterTalks";
container.add(new HTML("ShowFile"));
}
});
The code above (Client side code) not showing content of file its just downloading the file.
But I don't want user to download it, I want show them the content of it.
And, do I have to configure something over here to work it out.
resp.setContentType("text/plain");
resp.setHeader("Content-Disposition", "attachment; filename=output.txt");
Hope you got what my problem is. Please be free to share your thoughts and solutions to achieve this.
Thanks.
UPDATED
Up on the bases of first answer here, I changed some portion of my code:
updated code sections are:
resp.setHeader("Pragma", "no-cache");
final String url = "http://127.0.0.1:8888/FileUploadByWaterTalks";
String name = "output.txt";
Anchor link1 = new Anchor(name);
RootPanel.get().add(link1);
link1.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
Frame f = new Frame(url);
f.setSize("600px", "400px");
f.getElement().getStyle().setBorderWidth(0, Unit.PX);
RootPanel.get().add(f);
}
});
But still the browser asking me to save the file instead of showing it in the browser itself.
First remove the 'Content-Disposition' in your servlet.
Second, use a GWT Anchor in your code and when the user clicks open the link in a new window or an iframe.
Here you have a example using new window, and another using iframe:
final String url = "http://gwtquery.googlecode.com/git/README.txt";
String name = "README.txt";
Anchor link1 = new Anchor(name);
RootPanel.get().add(link1);
link1.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
Window.open(url, "_blank", "");
}
});
Anchor link2 = new Anchor(name);
RootPanel.get().add(link2);
link2.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
Frame f = new Frame(url);
f.setSize("600px", "400px");
f.getElement().getStyle().setBorderWidth(0, Unit.PX);
RootPanel.get().add(f);
}
});
This approach works for any file which the browser is capable to display, but be sure that you send the appropriate Content-Type header (text/plain, text/html, image/png etc.)
Is it possible to resend a RequestFactory transmission? I'd like to do the equivalent of this: How to resend a GWT RPC request when using RequestFactory. It is fairly simple to resend the same payload from a previous request, but I also need to place a call to the same method. Here's my RequestTransport class, and I am hoping to just "refire" the original request after taking care of, in this case, a request to the user for login credentials:
package org.greatlogic.rfexample2.client;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.web.bindery.requestfactory.gwt.client.DefaultRequestTransport;
/**
* Every request factory transmission will pass through the single instance of this class. This can
* be used to ensure that when a response is received any global conditions (e.g., the user is no
* longer logged in) can be handled in a consistent manner.
*/
public class RFERequestTransport extends DefaultRequestTransport {
//--------------------------------------------------------------------------------------------------
private IClientFactory _clientFactory;
//==================================================================================================
private final class RFERequestCallback implements RequestCallback {
private RequestCallback _requestCallback;
private RFERequestCallback(final RequestCallback requestCallback) {
_requestCallback = requestCallback;
} // RFERequestCallback()
#Override
public void onError(final Request request, final Throwable exception) {
_requestCallback.onError(request, exception);
} // onError()
#Override
public void onResponseReceived(final Request request, final Response response) {
if (response.getStatusCode() == Response.SC_UNAUTHORIZED) {
_clientFactory.login();
}
else {
_clientFactory.setLastPayload(null);
_clientFactory.setLastReceiver(null);
_requestCallback.onResponseReceived(request, response);
}
} // onResponseReceived()
} // class RFERequestCallback
//==================================================================================================
#Override
protected void configureRequestBuilder(final RequestBuilder builder) {
super.configureRequestBuilder(builder);
} // configureRequestBuilder()
//--------------------------------------------------------------------------------------------------
#Override
protected RequestCallback createRequestCallback(final TransportReceiver receiver) {
return new RFERequestCallback(super.createRequestCallback(receiver));
} // createRequestCallback()
//--------------------------------------------------------------------------------------------------
void initialize(final IClientFactory clientFactory) {
_clientFactory = clientFactory;
} // initialize()
//--------------------------------------------------------------------------------------------------
#Override
public void send(final String payload, final TransportReceiver receiver) {
String actualPayload = _clientFactory.getLastPayload();
TransportReceiver actualReceiver;
if (actualPayload == null) {
actualPayload = payload;
actualReceiver = receiver;
_clientFactory.setLastPayload(payload);
_clientFactory.setLastReceiver(receiver);
}
else {
actualReceiver = _clientFactory.getLastReceiver();
}
super.send(actualPayload, actualReceiver);
} // send()
//--------------------------------------------------------------------------------------------------
}
Based upon Thomas' suggestion I tried sending another request, and just replaced the payload and receiver in the RequestTransport.send() method, and this worked; I guess there is no further context retained by request factory, and that the response from the server is sufficient for RF to determine what needs to be done to unpack the response beyond the request and response that are returned to the RequestCallback.onResponseReceived() method. If anyone is interested in seeing my code then just let me know and I'll post it here.
It's possible, but you have a lot to do.
I had the same idea. And i was searching for a good solution for about 2 days. I tried to intercept the server call on RequestContext.java and on other classes. But if you do that you have to make your own implementation for nearly every class of gwt requestfactories. So i decided to go a much simpler approach.
Everywhere where I fired a Request, i handled the response and fired it again.
Of course you have to take care, that you don't get in to a loop.
I'm creating a small REST web service using Netbeans. This is my code:
private UriInfo context;
private String name;
public GenericResource() {
}
#GET
#Produces("text/html")
public String getHtml() {
//TODO return proper representation object
return "Hello "+ name;
}
#PUT
#Consumes("text/html")
public void putHtml(String name) {
this.name = name;
}
I'm calling the get method ok since when I call http://localhost:8080/RestWebApp/resources/greeting I get "Hello null" but I'm trying to pass a parameter using http://localhost:8080/RestWebApp/resources/greeting?name=Krt_Malta but the PUT method is not being called... Is this the correct way to pass a parameter or am I missing something?
I'm a newbie to Rest bdw, so sry if it's a simple question.
Thanks! :)
Krt_Malta
The second URL is a plain GET request. To pass data to a PUT request you have to pass it using a form. The URL is reserved for GET as far as I know.
If you build the HTTP-header yourself, you must use POST instead of GET:
GET /RestWebApp/resources/greeting?name=Krt_Malta HTTP/1.0
versus
POST /RestWebApp/resources/greeting?name=Krt_Malta HTTP/1.0
If you use a HTML-form, you must set the method-attribute to "PUT":
<form action="/RestWebApp/resources/greeting" method="PUT">
For JAX-RS to mactch a method annotated with #PUT, you need to submit a PUT request. Normal browsers don't do this but cURL or a HTTP client library can be used.
To map a query parameter to a method argument, JAX-RS provides the #QueryParam annotation.
public void putWithQueryParam(#QueryParam("name") String name) {
// do something
}
You can set:
#PUT
#path{/putHtm}
#Consumes("text/html")
public void putHtml(String name) {
this.name = name;
}
and if you use something like google`s Volley library you can do.
GsonRequest<String> asdf = new GsonRequest<String>(ConnectionProperties.happyhourURL + "/putHtm", String.class, yourString!!, true,
new Response.Listener<Chain>() {
#Override
public void onResponse(Chain response) {
}
}, new CustomErrorListener(this));
MyApplication.getInstance().addToRequestQueue(asdf);
and GsonRequest will look like:
public GsonRequest(String url, Class<T> _clazz, T object, boolean needLogin, Listener<T> successListener, Response.ErrorListener errorlistener) {
super(Method.PUT, url, errorlistener);
_headers = new HashMap<String, String>();
this._clazz = _clazz;
this.successListener = successListener;
this.needsLogin = needLogin;
_object = object;
setTimeout();
}