AJAX server mockup - java

I am having a Java applet developed on my behalf. The applet makes AJAX requests to a server. I have not written the server code yet.
Is there a design pattern I can use to mock the server responses, whilst the server is not yet ready, so that the applet can be developed and tested against this "mock server"?
Some sample code on how to implement the mockup server would be very useful

Although I'm not entirely sure if this suits your needs, but you can checkout a simple class I made for this purposes here. Here is some sample code:
//let's say that when you GET to /users?id=2 the server should return the user with id 2
//first start the server on your favourite port
MockHttpServer server = new MockHttpServer(portNum);
server.start();
//We will add a mock response for every request we will do, so in this case, just one mock response
server.enqueueResponse(Status.OK, "application/json,"{\"user_id\":15,\"name\":\"paul\"}");
//now we will use curl or whatever to make the GET
curl http://0.0.0.0:3000/users?id=2
// we get the request object
Request req = server.getRequest();
assertEquals(req.getMethod(),"GET");
assertEquals(req.getParams().get("id"),"2")
Its still a work in progress but you can get an idea by reading the code on github. Hope it helps :)

Related

Making HTTP request and using cookies

I am working on an app that will help me log in the website and view data that I need. While I have no trouble with making sure that I parse that data and work with it properly, I did face an issue with logging into the website. I tried sending POST request, yet that didn't really work for some reason so I started looking more closely into how POST request to that website is sent in the browser and here is what I got:
Picture
I also asked a guy who developed that website and he said that I should use two cookies with "ulogin" and "upassword" for my log in. I tried using JSOUP as shown right here: https://jsoup.org/cookbook/input/load-document-from-url
I used .cookies("upassword", "10101010"), yet it didn't work so it makes me think that there is a bit more to it than just writing a simple line a post request.
Please, can someone explain to me how do I use cookies to log into website or at least point me in the direction where I can learn that, because I am so close to making that app happen and I will be able to proceed further with it's development, but it's just this one step that I am really being stuck with.
Here is an additional picture with Response and Request Headers from the Firefox. Picture
I managed to get it working a long time, yet didn't post an answer. So, here we go.
Cookies are just simple Headers, therefore you should treat them as such. In my case, with the use of HttpURLConnection, here is a piece of working code:
Note: My original request is for Java, however, I have since moved to Kotlin, so this solution uses Kotlin and this function is a "suspend" function which means that it is designed to be used with Kotlin Couroutines.
suspend fun httpRequest(): String {
val conn: HttpURLConnection = url_profile.openConnection() as HttpURLConnection
conn.requestMethod = "POST"
conn.doOutput = true
conn.doInput = true
conn.setRequestProperty(
"Cookie",
"YOUR COOKIE DATA"
)
val input: BufferedReader = BufferedReader(InputStreamReader(conn.inputStream))
return input.readText()
}

java httpServer Post request work

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.

soap set parameter java

I am implementing a TV listing service and I have decided to use ROVI as my data provider.
They provide me with an API that allows me to exchange data between my application and their servers by means of SOAP requests.
Since I am programming in Java, I used wsimport to generate the classes that would enable me to interact with their server.
//Connection
service = new ListingsService();
port = service.getListingsServiceSoap();
I have come across a problem which Google doesn't seem to have the answer for.
According to their API, whenever I want to make a call to a SOAP service I have to add my API Key to the end of url.
The problem is, I don't know how to do that. Using the stubs generated by wsimport, I can create a request object as it should be; however the URL is not displayed as per their specification. The url I currently get is: http://api.rovicorp.com/v9/listingsservice.asmx and what is required is: http://api.rovicorp.com/v9/listingsservice.asmx?apikey=myAPIkey. I obtained that by printing the following code:
System.out.println(port.toString());
Trying to run the following code:
GetServicesRS servicesRS = port.getServices(getServicesRQ, auth)
Yields the following error:
Exception in thread "main" com.sun.xml.internal.ws.client.ClientTransportException: The server sent HTTP status code 403: Forbidden
What java method can I use to append this parameter into the SOAP request URL.
Thanks for your help.
Edit.
I am still struggling with this and haven't been lucky with responses, if anyone could point me in the direction of a framework or something that could facilitate this would be great!
Cheers
I manage to work around my problem using something called BindingProvider.
I added the following to my code:
//Connection
service = new ListingsService();
port = service.getListingsServiceSoap();
BindingProvider bindingProvider = (BindingProvider) port;
bindingProvider.getRequestContext()
.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
"http://api.rovicorp.com/v9/listingsservice.asmx?apikey=" + APIKey);
With the aforementioned code the call to the API is successful:
GetServicesRS servicesRS = port.getServices(getServicesRQ, auth)
Hope it helps someone in the future.

Play-Framework & Ajax how to?

I'm looking to do the following with AJAX...
I have a request to my server that takes a considerable amount of time to complete. The request is made in the controller and upon completion a HTML page is loaded informing the user of its completion.
However, what I'd like to do is have the request sent asynchronously, load the completion page and then load the requests result once it become available. I assume I would use AJAX to do this but I'm not exactly sure how. Can anyone point me to a good guide for doing something like this?
In case my explanation above is too confusing here is what I want to do...
1) Send request to server from Controller asyncronously.
2) load HTML page.
3) When request has completed fill field in already loaded HTML page with the response from the request.
I wrote a tutorial recently that walks through how to do this with Play 1.2, JSON, and jQuery:
Tutorial: Play Framework, JPA, JSON, jQuery, & Heroku
There are 2 parts you need to take into account here:
The client side
The server side
For the client side; an Ajax request (for example, using jQuery.ajax) is per definition asynchronous. This means that you should be able to do the following - again using jQuery, which makes things easier - in your HTML page:
// The ready handler, which fires when the page has been loaded
$(function() {
jQuery.ajax(
// Do your thing here
);
});
For the server side; in case your operation is going to be running for a relatively long time on the server (for instance several web service calls or long running IO operations) you'll want to use Play's asynchronous capabilities to let the Play! server execute things as effeciently as possible. It does this by offloading the long running operation(s) to their own threads.
The only thing left to do is set-up a route to your controller, implement the handler method and render something that your client-side JavaScript code is capable of parsing (JSON is probably the easiest, using Play's renderJson()).
I haven't used this set-up myself - maybe someone can confirm this would be the way to do it?

Is it possible to access the html of a site with a 204 response code via java.net?

I am trying to read a website using the java.net package classes. The site has content, and i see it manually in html source utilities in the browser. When I get its response code and try to view the site using java, it connects successfully but interprets the site as one without content(204 code). What is going on and is it possible to get around this to view the html automatically.
thanks for your responses:
Do you need the URL?
here is the code:
URL hef=new URL(the website);
BufferedReader kj=null;
int kjkj=((HttpURLConnection)hef.openConnection()).getResponseCode();
System.out.println(kjkj);
String j=((HttpURLConnection)hef.openConnection()).getResponseMessage();
System.out.println(j);
URLConnection g=hef.openConnection();
g.connect();
try{
kj=new BufferedReader(new InputStreamReader(g.getInputStream()));
while(kj.readLine()!=null)
{
String y=kj.readLine();
System.out.println(y);
}
}
finally
{
if(kj!=null)
{
kj.close();
}
}
}
Suggestions:
Assert than when manually accessing the site (with a web browser client) you are effectively getting a 200 return code
Make sure that the HTTP request issued from the automated (java-based) logic is similar/identical to that of what is sent by an interactive web browser client. In particular, make sure the User-Agent is identical (some sites purposely alter their responses depending on the agent).
You can use a packet sniffer, maybe something like Fiddler2 to see exactly what is being sent and received to/from the server
I'm not sure that the java.net package is robot-aware, but that could be a factor as well (can you check if the underlying site has robot.txt files).
Edit:
assuming you are using the java.net package's HttpURLConnection class, the "robot" hypothesis doesn't apply.
On the other hand you'll probably want to use the connection's setRequestProperty() method to prepare the desired HTTP header for the request (so they match these from the web browser client)
Maybe you can post the relevant portions of your code.

Categories

Resources