POST request on a https server in JAVA - java

I came here to ask my question after searching for 2 days !! My question is about REST api call and POST request on my api. I have already seen tutorial in JAVA about creating a httpclient in my side with httpsURLConnection to connect to the api and I did a POST request. It works for instance with https://www.example.com. BUT it did not work for the case below.
Case: (I have to do that in JAVA with eclipse)
The REST API is accessible at https://test.api.kolibree.com. I get a client_id (=5)
and a client_secret (= X7doOhLCRbuT0FIgBsmy) to access the API. First, to make an API call, I need to provide the http-x-client-idand http-x-client-sig headers. http-x-client-sigis computed using the absolute url of the request. (I managed to compute it)
Secondly: to connect to a Kolibree account using an email and a password, make a POST request to v1/accounts/request_token/ with body arguments email (=android.test#kolibree.com) and password (=test).
Problem:
I don't know how to handle the client id and signature headers to do an API call. I haven't seen any tutorials talking about that. Furthermore, how to handle the email and password to do a POST request.
Thanks a lot for your kind attention. I would be infinitely thankful.
Alex

Would this be an example of doing HTTP POST with parameters?
https://hc.apache.org/httpcomponents-client-ga/quickstart.html

Related

How to read websocket response code through automation scripts

Suppose I have a resource that is hosted on a websocket server, and I wish to validate the response status code 101, after the connection is upgraded, how and which libraries to use.
Im currently looking at jayway response library, when I connect to a websocket resource, initially it sends a 200 and then upgrades to 101. So code returns 200, I would like to know how this library can be used for websocket validation.
Sample code is :
String response =given().get()("https://www.ws.com:444/examples/websocket/snake.xhtml")
.getResponse().asString();
This returns a 200, but does not return the next response. I might sound a little rusty here, would appreciate if you folks have any idea how to extend it to get status 101 or if you have any other suggestions.
Also, this requirement needs to be extended to handle redirection 30x status codes as well, assume a resource is protected behind an access gateway, when a request comes for this protected resource, the gateway forwards it to identity store for verifying the user, at this time a 302 is returned, once verified, request is sent back to access gateway from where user is able to access websocket resource.

How to build HTTP DELETE request with JSON encoded body using AsyncHttpClient

I need to write a HTTP client which to communicate with Floodlight OpenFlow controller via its REST API.
For testing I did it in python, and it worked OK. But now I'm in a situation where it has to be done in Java, of which I'm admittedly still at the beginner's level. One of my apps uses AsyncHttpClient to dispatch async GET requests, and works just fine. Now as a Floodlight's REST client, it has to do POST and DELETE with JSON encoded body. My code for an async POST request works very much as expected.
But no luck with DELETE.
Somehow it doesn't write JSON string into its request body.
The code is almost identical with POST. For debugging, I don't feed an AsyncCompletionHandler instance to execute() method.
System.out.println(ofEntry.toJson()); // this returns {"name": "xyz"} as expected.
Future<Response> f = httpClient.prepareRequest(new RequestBuilder("DELETE")
.setUrl("http://" + myControllerBaseUrl + urlPathFlowPostDelete)
.setHeader("content-type", "application/json")
.setBody(ofEntry.toJson())
.build()).execute();
System.out.println(f.getStatusCode()); // returns 200.
System.out.println(f.getResponseBody()); // returns {"status" : "Error! No data posted."}.
Just to make sure, I peeped into packet dump with wireshark, and found out the server isn't lying :)
The author of the library has written an extensive amount of relevant, valuable information, but unfortunately I can't find example code specifically for building a DELETE request.
I'd very much appreciate any suggestions, pointers, and of course pinpoint solutions!
Not sure that replying to my own question is appropriate here, but I have just found a related thread at the floodlight-dev Google group.
Problem with Static Flow Pusher DELETE REST method
So this could be a problem with Floodlight REST API which requires message body for a DELETE request to identify what to be deleted, whereas AHC is simply compliant with RFC2616.
I will follow the thread at Google group, and see how it will conclude among developers.

Open an authenticated image served by django from java using Apache http client

I Am serving an authenticated image using django. The image is behind a view which require login, and in the end I have to check more things than just the authentication.
Because of a reason to complicated to explain here, I cannot use the real url to the image, but I Am serving it with a custom url leading to the authenticated view.
From java the image must be reachable, to save or display. For this part I use Apache httpclient.
In Apacahe I tried a lot of things (every example and combination of examples...) but can't seem to get it working.
For other parts of the webapp I use django-rest-framwork, which I succesfully connected to from java (and c and curl).
I use the login_reuired decorator in django, which makes the attempt to get to the url redirect to a login page first.
Trying the link and the login in a webviewer, I see the 200 code (OK) in the server console.
Trying the link with the httpclient, I get a 302 Found in the console.... (looking up 302, it means a redirect..)
this is what I do in django:
in urls.py:
url(r'^photolink/(?P<filename>.*)$', 'myapp.views.photolink',name='photolink'),
in views.py:
import mimetypes
import os
#login_required
def photolink(request, filename):
# from the filename I get the image object, for this question not interesting
# there is a good reason for this complicated way to reach a photo, but not the point here
filename_photo = some_image_object.url
base_filename=os.path.basename(filename_photo)
# than this is the real path and filename to the photo:
path_filename=os.path.join(settings.MEDIA_ROOT,'photos',mac,base_filename)
mime = mimetypes.guess_type(filename_photot)[0]
logger.debug("mimetype response = %s" % mime)
image_data = open(path_filename, 'rb').read()
return HttpResponse(image_data, mimetype=mime)
by the way, if i get this working i need another decorator to pass some other tests....
but i first need to get this thing working....
for now it's not a secured url.... plain http.
in java i tried a lot of things... using apache's httpclient 4.2.1
proxy, cookies, authentication negociation, with follow redirects... and so on...
Am I overlooking some basic thing here?...
it seems the login of the website client is not suitable for automated login...
so the problem can be in my code in django....or in the java code....
In the end the problem was, using HTTP authorization.
Which is not by default used in the login_required decorator.
adding a custom decorator that checks for HTTP authorization did the trick:
see this example: http://djangosnippets.org/snippets/243/

FB is sending me a non-URL safe code

FB is sending me a non-URL safe code. While implementing the oauth authentication, FB is sending me a code parameter that is non-url safe.
When i authorize the app i am getting the code parameter with the below value which is not url safe.
AQBQnGZgFNv5EcIB9hZI20GcUgBWru7TE-p_G5NB2HQLX87fyc463aM0BIAiBg_PwRiIuyo0KS1vrDLOLB_SQ0goY31RrNYtZ23lOeaOkGzztarMYH8bJpSYjFOgiXbPhcP6h9YCsizekmcbLpPX_3F7qhsZOLM37UGI7QysvyYOvptpgJ-fm5t-eSViIU_CQH8jTPcQu3BylUVIXS0cEt5T#___=_
When FB is redirecting the control to the my url which is a java web application, i tried to get the code parameter using the code "request.getParameter(CODE)" But i am getting only
AQBQnGZgFNv5EcIB9hZI20GcUgBWru7TE-p_G5NB2HQLX87fyc463aM0BIAiBg_PwRiIuyo0KS1vrDLOLB_SQ0goY31RrNYtZ23lOeaOkGzztarMYH8bJpSYjFOgiXbPhcP6h9YCsizekmcbLpPX_3F7qhsZOLM37UGI7QysvyYOvptpgJ-fm5t-eSViIU_CQH8jTPcQu3BylUVIXS0cEt5T
without #___=_
so i am not able to continue further. But i manually add it to the parameter to fetch the access token it is working fine.
Why is this happening? Please help me.
i think this is signed_request code.
You doesn't need the #_=_ trail to get further, it's not a part of signed_request or code for OAuth2. If you can proceed to further steps it's something other that this.
Once you get code passed to redirect_uri URL you can continue with authentication:
In order to authenticate your app, you must pass the authorization code and your app secret to the Graph API token endpoint - along with the exact same redirect_uri used above - at https://graph.facebook.com/oauth/access_token.
https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&
client_secret=YOUR_APP_SECRET&code=THE_CODE_FROM_ABOVE

Write proxy/wrapper class for own service in jersey

I want to access a full rest service with basic http auth running.
However there is no way to for the javascript browser client to suppress the authenticate box when a wrong credential is provided.
I thought about different methods to solve this problem
someone suggested to remove the WWW-Authenticate Header with a filter (i dont think this is a clean approach)
i could rewrite my app to not use Basic Http Auth at all (i think this is too much trouble)
i could write a proxy that talks to my regular service
I like the last approach the best.
I keep my regular Rest Interface, but also have the option to use this interface with clients that are not that flexible.
Furthermore I can later proxy Http Requests unsupported by some browsers.
The idea is to have a /api/proxy/{request} path that proxies to /api/{request} and returns a Facebook-Graph-like JSON query { data: {data}, error: {error}}
This is the stub of the Proxy class
#Path("proxy")
public class ProxyResource {
#GET()
#Path("{url: [a-zA-Z/]*}")
public String get(#Context Request request, #PathParam("url") String url) {
// remove proxy/ from path
// resend request
// verify result
}
}
I can access the Request (which seems to be a ContainerRequest). How can I modify the request without building it from scratch to resend it.
Edit: when somebody knows a better approach i am delighted to hear about it.
As I started to digg deeper into this, i found out that not the 401 was the problem. The www-authenticate header sent back from the server caused the browser to open the login box.
If somebody is interested I've written a little nodejs proxy to remove a www-authenticate from all server requests.
https://gist.github.com/ebb9a5052575b0a3f41f
As this is not the answer to my original question I will leave it open.

Categories