66305
HI,
I want to invoke a Servlet from the client side, as a Onclick event on a Button in java programming language.
I read somewhere through anchor tag we can call a servlet, but i did not figure out the solution or Syntax properly.
Anyone please me.
Thanks,
sekhar
Typically you use a RemoteService to communicate with a server. To do that, you create an interface that extends RemoteService and an implementation on the server that implements that interface and extends RemoteServiceServlet. All that is described in more detail here. If you need to make a call to some servlet that isn't a remote service servlet, you can use RequestBuilder to send an HTTP request to that servlet's URL.
An Anchor is basically just a normal HTML <a> tag which could link to the URL of a servlet.
You have to manually create one httpClient & call GET/POST method.
Below is sample code using POST method:
//---
HttpClient client = new HttpClient();
BufferedReader br = null;
PostMethod method = new PostMethod("http://someUrl.com");
method.addParameter("p", "\"parameter\"");
int statusCode = client.executeMethod(method);
if(statusCode == HttpStatus.SC_NOT_IMPLEMENTED) {
System.out.println("Not Supported");
method.getResponseBodyAsString();
} else {
br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
String readLine;
while(((readLine = br.readLine()) != null)) {
System.out.println(readLine);
}
}
//---
Related
I have the following curl request:
curl -X GET http://hostname:4444/grid/api/hub -d '{"configuration":["slotCounts"]}'
which returns a JSON object.
How can I make such request and get the response in Java? I tried this:
URL url = new URL("http://hostname:4444/grid/api/hub -d '{\"configuration\":[\"slotCounts\"]}'");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
url.openStream(), "UTF-8"))) {
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
}
But it returns an exception:
Caused by: java.io.IOException: Server returned HTTP response code: 400 for URL: http://hostname:4444/grid/api/hub -d '{"configuration":["slotCounts"]}'
Based on the comments, managed to solve it myself.
private static class HttpGetWithEntity extends
HttpEntityEnclosingRequestBase {
public final static String METHOD_NAME = "GET";
#Override
public String getMethod() {
return METHOD_NAME;
}
}
private void getslotsCount() throws IOException,
URISyntaxException {
HttpGetWithEntity httpEntity = new HttpGetWithEntity();
URL slots = new URL("http://hostname:4444/grid/api/hub");
httpEntity.setURI(pendingRequests.toURI());
httpEntity
.setEntity(new StringEntity("{\"configuration\":[\""
+ PENDING_REQUEST_COUNT + "\"]}",
ContentType.APPLICATION_JSON));
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(getPendingRequests);
BufferedReader rd = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
// At this point I can just get the response using readLine()
System.out.println(rd.readLine());
}
That's not how sending data in Java works. The -d flag is for the CURL CLI only. In Java you should use a library like Apache HTTP Client:
https://stackoverflow.com/a/3325065/5898512
Then parse the result with JSON: https://stackoverflow.com/a/5245881/5898512
As per your exception/error log, it clearly says that the service http://hostname:4444/grid/api/hub is receiving bad request(Status code 400).
And i think you need to check the service to which you are hitting and what exactly it accepts. Ex: the service may accept only application/json / application/x-www-form-urlencoded or the parameter to service that expecting but you are not sending that.
When I make a request to : " https://www.btcturk.com/api/orderbook " via browser or curl I get the response as expected.
When I make the same request via jersey or java libraries such as HttpsURLConnection, I get a 403 forbidden response.
I can use the same methods to make requests to any other urls running under https. An example method can be found below :
public static RestResponse getRestResponse(String url)
{
String jsonString;
try
{
Client client = Client.create();
WebResource webResource = client.resource(url);
ClientResponse response = webResource.accept("application/json")
.get(ClientResponse.class);
if (response.getStatus() != 200) {
return RestResponse.createUnsuccessfulResponse(response.getStatusInfo().getReasonPhrase());
}
jsonString = response.getEntity(String.class);
}
catch(Exception e)
{
return RestResponse.createUnsuccessfulResponse(e);
}
return RestResponse.createSuccessfulResponse(jsonString);
}
The above code is just to give the idea. The whole thing can be found at: https://github.com/cgunduz/btcenter/tree/master/src/main/java/com/cemgunduz/web
My network knowledge is very limited, so any directions towards where I should start would be helpful. Cheers.
You probably have to provide some credentials. Depending on the server configuration you have to provide either a user/password combination or a valid certificate. Try the solutions provided here:
Using HTTPS with REST in Java
I am writing a client for Restful web services.
public static void main(String[] args){
// Use apache commons-httpclient to create the request/response
HttpClient client = new HttpClient();
Credentials defaultcreds = new UsernamePasswordCredentials("aaa", "cdefg");
client.getState().setCredentials(AuthScope.ANY, defaultcreds);
GetMethod method = new GetMethod(
"http://localhost:8080/userService/usersByID/1234");
try {
client.executeMethod(method);
InputStream in = method.getResponseBodyAsStream();
// Use dom4j to parse the response and print nicely to the output stream
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println(out.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
I am getting unauthorized error 401. When I checked the server logs. I found the following.
ERROR httpclient.HttpMethodDirector - Credentials cannot be used for NTLM authentication: org.apache.commons.httpclient.UsernamePasswordCredentials
So, I understood that I need to use NTLM authentication for this.
Can some one tell me how to modify this to do NTLM authentication.
Thanks in Advance.
Please check the below links
http://hc.apache.org/httpclient-3.x/authentication.html#NTLM
http://davenport.sourceforge.net/ntlm.html
Instead of setCredentials try using setProxyCredentials.
client.getState().setProxyCredentials(AuthScope.ANY, defaultcreds);
Does anyone have a good tutorial on how to write a java or javafx cURL application? I have seen tons of tutorials on how to initiate an external call to say like an XML file, but the XML feed I am trying to retrieve calls for you to submit the username and password before being able to retrieve the XML feed.
What are you trying to accomplish? Are you trying to retrieve a XML feed over HTTP?
In that case I suggest you to take a look at Apache HttpClient. It offers similair functionality as cURL but in a pure Java way (cURL is a native C application). HttpClient supports multiple authentication mechanisms. For example you can submit a username/password using Basic Authentication like this:
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 443),
new UsernamePasswordCredentials("username", "password"));
HttpGet httpget = new HttpGet("https://localhost/protected");
System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
if (entity != null) {
entity.consumeContent();
}
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
Check the website for more examples.
I am using Apache's HttpCommons 3.1 package to login to a website.
The website is a jsp page with the form using j_security_check along with j_username and j_password.
From a browser, I would do the following:
Go to the Login.jsp page
Fill in user name and password
Click on login button
With the valid username and password, I would get into the restricted resources. Sounds simple enough, the problem is I have been trying to do this via a simple java application using Apache's HttpCommons 3.1 package (HttpClient, GetMethod, PostMethod etc.) and I have been getting 302-resource moved from the server.
Here is my source code:
String strURL = "http://host:port/app/login/LoginForm.jsp";
HttpState initialState = new HttpState();
HttpClient httpclient = new HttpClient();
httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
httpclient.setState(initialState);
httpclient.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
GetMethod httpget = new GetMethod(strURL);
int result = httpclient.executeMethod(httpget);
System.out.println("Response status code: " + result);
Cookie[] cookies = httpclient.getState().getCookies();
String res1 = httpget.getResponseBodyAsString();
httpget.releaseConnection();
PostMethod postMethod = new PostMethod("http://host:port/app/j_security_check");
NameValuePair[] postData = new NameValuePair[2];
postData[0] = new NameValuePair("j_username", "username");
postData[1] = new NameValuePair("j_password", "password");
postMethod.addParameters(postData);
postMethod.addRequestHeader("Referer",strURL);
for (int i = 0; i < cookies.length; i++)
{
initialState.addCookie(cookies[i]);
}
httpclient.setState(initialState);
try
{
httpclient.executeMethod(postMethod);
}
catch (HttpException httpe)
{
System.err.print("HttpException");
System.err.println(httpe.getMessage());
httpe.printStackTrace();
}
catch (IOException ioe)
{
System.err.print("IOException");
System.err.println(ioe.getMessage());
ioe.printStackTrace();
}
String res2 = postMethod.getResponseBodyAsString();
postMethod.releaseConnection();
System.out.println(res2);
}
catch (IOException ex)
{
//print out ...
}
I had tried the same type of an example against the same server using PHP code (CURL) and I do get forwarded to the page I would expect after a successful login.
Any idea why the same is not working in Java?
Thanks,
- MK
You need to call postMethod.setFollowRedirects(true).
The 302 is a redirect to the post login page.
It's possible that HttpCommons doesn't support 302, try HttpUnit.
Per the documentation on the website (http://hc.apache.org/httpclient-3.x/redirects.html), HttpClient doesn't handle certain redirects by default because the authors feel they're best handled by the user. If you're looking at scraping web sites for certain content, I've used a library called WebHarvest to great success in the past. You can find it on sourceforge : http://web-harvest.sourceforge.net/