I am trying to download spreadhseets from a users google drive. I am encountering a CORS issue.
http://javascript.wekeepcoding.com/article/15417055/CORS+on+exportLinks+for+Google+Docs+spreadsheets+not+working
Reading this:
https://github.com/google/google-api-javascript-client/issues/47
I am trying to make a GET request on the server side. I tried using restTemplate.exchange but I am not sure what format my response should be in. Basically completely lost.
Is there a way to make the GET to pull the file and pass back to my front end?
I keep getting this error for whatever format I try:
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [interface java.sql.Blob] and content type [application/vnd.openxmlformats-officedocument.spreadsheetml.sheet]
Any help greatly appreciated.
As far as CORS goes, this is the relevant guide I can find, How to use CORS to access Google APIs
Use XMLHttpRequest2 to make
CORS requests.
A CORS request to a Google API is similar to a REST request. The URL
for a CORS request follows this pattern:
https://www.googleapis.com +
REST path + URL Params
Example: here is a REST request:
var restRequest = gapi.client.request({
'path': 'https://people.googleapis.com/v1/people/me/connections',
'params': {'sortOrder': 'LAST_NAME_ASCENDING'}
});
And here is the equivalent CORS request:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://people.googleapis.com/v1/people/me/connections?sortOrder=LAST_NAME_ASCENDING');
Request headers are added to the request using
XMLHttpRequest.setRequestHeader.
The request body is sent using the XMLHttpRequest.send method.
You can register callbacks by adding event listeners on the load and
error events. Follow this link for information about XMLHttpRequest
events
Also make sure you have permission to download the spreadsheet file
from the other user.
Related
I'm start learning java programming, and I want make a simple server application. I read about com.sun.net.httpserver.HttpServer and find a good example on this link: https://github.com/imetaxas/score-board-httpserver-corejava.
I understand how to do Get-request in url, but I don't know how POST works. I think it must be sent a form or data on the server.
I attach the link of project, which I'm learning, in readme the author wrote http://localhost:8081/2/score?sessionkey=UICSNDK - it's not working...
I wrote in url and get sessionkey: "localhost:8081/4711/login --> UICSNDK"
I wrote in url this for Post request: "localhost:8081/2/score?sessionkey=UICSNDK" - not working and in chrome return 404 bad request
3.wrote in url this:"localhost:8081/2/highscorelist"
Please help me, I am beginner.
The difference between GET and POST is that with a GET request the data you wish to pass to the endpoint is done by modifying the url itself by adding parameters to it.
With a POST any data you wish to send to the endpoint must be in the body of the request.
The body of a request is arbitrary data that comes after a blank line in the header The reqiest has the request line, following by any number of header attributes, then a blank line.
The server would need to know what the format of the body of the request was and parse it as appropriate.
Of course 'modern' frameworks like jax-rs allow you to automatically convert request data to objects, so that it is much simpler.
I have a simple REST client with some basic functionality, and so far I'm stuck as I don't know how to process those request and send them correctly into the server. So far I've tried this in the filter, without any luck.
if (!request.getHeader("/rest/").equals(null)){
String loginForm = config.getInitParameter("LoginParam");
res.sendRedirect(req.getContextPath() + loginForm);
return;
}
And I get the following error because of that deny.
Exception in thread "main" org.jboss.resteasy.client.ClientResponseFailure
How should I check that the request is coming from the REST client so I can let it pass through?
I'd normally add header Accept: application/json (or xml or whatever) to indicate the client wants to get data as oppose to HTML.
even though i have appended my service response with following provided CORS Headers :
resp.setContentType("application/json");
resp.addHeader("Access-Control-Allow-Origin", "*");
resp.addHeader("Access-Control-Allow-Credentials", "true");
resp.addHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
resp.addHeader("Access-Control-Allow-Headers", "Origin,accept,content-type");
resp.flushBuffer();
i am still getting below error in the console while trying to access some of the POST web methods in the service through my AngularJS frontend.
XMLHttpRequest cannot load http://192.***.*.***:8080/abc/def/search/vehicleManufacturer. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.***.*.***:8085' is therefore not allowed access.
However within the same class, some POST methods without any payloads are responding perfectly. Any suggestions ?
EDIT--------->
Below is my AngularJS client screen code for calling the web method:-
getVehicleModel : function(searchData,$scope){
$http({
method:'POST',
url:'http://192.169.*.***:8085/abc/def/search/vehicleModel',
dataType:'jsonp',
data:searchData
}).
success(function(data){
console.log("vehicle model")
$scope.vehicleModel = data.Response;
});
},
I think the problem here is Preflighted Requests in CORS.
From the Mozilla docs,
Unlike simple requests (discussed above), "preflighted" requests first
send an HTTP request by the OPTIONS method to the resource on the
other domain, in order to determine whether the actual request is safe
to send. Cross-site requests are preflighted like this since they may
have implications to user data. In particular, a request is
preflighted if:
It uses methods other than GET, HEAD or POST. Also, if POST is used to send request data with a Content-Type other than
application/x-www-form-urlencoded,
multipart/form-data
text/plain
e.g. if the POST request sends an XML payload to the server using application/xml or text/xml, then the request is preflighted.
It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)
As explained above, even though you're making a simple POST request, the Content-Type in your request is application/json which is different from the 3 types mentioned above, so it's considered as a Preflight request and an OPTIONS request is fired before your actual POST request.
You can solve this by implementing doOptions in your servlet, just add the headers there and it will work :)
The preflight (OPTIONS) is occurring due to the fact that you are sending a cross-origin ajax request AND specifying an Authorization header with this GET request.
Also (this is not causing an issue) I would suggest removing the contentType option. This doesn't make sense in the context of a GET request. A GET request should not have any content. All data should be included in the query string or, possibly, headers.
The Authorization header will not be sent with the OPTIONS. You must acknowledge it server-side, and then the browser will send the underlying GET. Read more about CORS at https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS .
I'm in the process of learning how to use HP Quality Center's REST api to query and manipulate data. Unlike REST standard, this API is not completely stateless. It uses cookies to store authentication sessions.
I've tried to implement a very simple test, using the Jersey Client library. I can successfully authenticate my user, by sending my credentials. The API reference claims that this will set a cookie, and I am good to go with further calling the REST api. However, a simple "is-authenticated" call returns a 401, Authentication failed.
I have a feeling that the cookie writing or reading is not working properly, as everything else seems to work as it should. But I haven't been able to find out if or how cookies are set and read, when no browser is involved. So How does cookies work, when calling cookie-setting REST services from java VM? Does it work at all? Where are they stored?
I am using Eclipse Kepler as my IDE, if that matters at all, and a 32-bit java 1.6 JDK and JRE.
Code, and response strings below:
1. Logging in:
Client client = ClientBuilder.newClient();
Response response = client
.target("http://[host]:[port]").path("qcbin/authentication-
point/alm-authenticate")
.request().post(Entity.entity("<alm-authentication>
<user>username</user>
<password>secret</password></alm-authentication>",
MediaType.TEXT_XML_TYPE));
System.out.println(response.toString());
Output:
InboundJaxrsResponse{ClientResponse{method=POST,
uri=http://[host]:[port]/qcbin/authentication-point/alm-authenticate,
status=200, reason=OK}}
API Return description:
One of:
HTTP code 200 and sets the LWSSO cookie (LWSSO_COOKIE_KEY).
HTTP code 401 for non-authenticated request. Sends header
WWW-Authenticate: ALMAUTH
2. Verifying Logged in:
response = client.target("http://[host]:[port]")
.path("qcbin/rest/is-authenticated")
.request().get();
System.out.println(response.toString());
Output:
InboundJaxrsResponse{ClientResponse{method=GET,
uri=http://[host]:[port]/rest/is-authenticated, status=401,
reason=Authentication failed. Browser based integrations - to login append
'?login-form-required=y to the url you tried to access.}}
PS: adding the ?login-form-required=y to the URL, will bring up a log-in window when called in a browser, but not here. Appending the line to the URL actually still gives the same error message, and suggestion to append it again. Also, when called in a browser, the is-authenticated returns a 200, success, even without the login-form.
When you log in, you're getting a cookie which is a name plus a value.
The REST server expects you to pass this in the request header with every request you make.
Look into the object which you get for client.request(); there should be a way to specify additional headers to send to the server. The header name must be Cookie and the header value must be name=value.
So if the server responds with a cookie called sessionID with the value 1234, then you need something like:
client.request().header("Cookie", "sessionID=1234")
Related:
http://en.wikipedia.org/wiki/HTTP_cookie
I have a social networking site in which we have a restricted community.
When a guest user applies requests for membership, a membership request is generated. I am performing this task through a REST API.
I am using RESTClient plugin in firefox to send requests.
When I send a POST resquest for adding self to the restricted community, the response is the memebership request generated for the same. Hence, the underlying HTTP status code is 303 See Other POST/GET.
I get proper response for the same with the membership request in response but the status code is 200 OK(which I think is the code for the GET on the membership request).
But, I need the same to be 303. I have tried debugging also. My finding is that the Jersey Response.seeOther() is not returning 303.
Please help.
The code snippets are as follows :
addUserToCommunity method :
MembershipRequestModel membershipRequest = null;
membershipRequest = communityService.addUserToCommunity(communityId, userId);
if(membershipRequest != null) {
// Add code 303 if returning membershiprequest
return seeOther( membershipRequest,
String.valueOf(membershipRequest.getId()),
MembershipRequestRestHandlerImpl.class);
} else {
return ok(null);
}
seeOther method which in turn calls Response.seeOther() :
public Response seeOther(Object model, String id, Class<?> resource){
URI location = buildLocation(resource, id);
return Response.seeOther(location).entity(createResponseItems(model)).build();
}
303 - See Other is essentially a redirect - browser would automatically follow the URL provided in location header. Are you sure this is not what you see? I.e. maybe the firefox plugin you are using is simply following the redirect (behind the scenes) and returning the result of a GET method on that location URL. Try FireBug which shows you exact requests that went on the wire - you should be able to see the redirect there.
If you want to geht the 303 instead of the 200 Response:
httpClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
The redirect URL ist in the Location: header
This is actually a problem with RESTClient i.e; the browser as Martin says.
The browser actually performs the redirect and does not give 303.
Instead try hitting the URI using cURL in the shell or using puTTY. It works fine.
Thank you.