In this
tutorial written how to create REST service and how to consume it. I confused by consuming example. There we need to have on client side jersey.jar and write like this:
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());
Why client need to know how web-service implemented(jersey or may be ohter implementation)? Why client side don't consume it by using simple InputStream?
In this particular tutorial you are using the jersey CLIENT to interact with a RESTful Service.
You could also just interact with the service directly by just manually creating an HTTP request and receiving the response and parsing accordingly(http://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html).
The Jersey client is ultimately is just an abstraction of this to make it easier to work with.
String URL ="http://localhost:8080/MyWServices/REST/WebService/";
String ws_method_name = "getManagerListByRoleID";
String WS_METHOD_PARAMS = "";
HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(URL + ws_method_name + WS_METHOD_PARAMS);
String text = null;
try {
HttpResponse httpResponse = httpClient
.execute(httpGet, httpContext);
HttpEntity entity = httpResponse.getEntity();
text = getASCIIContentFromEntity(entity);
}catch(Exception e){
e.printStackTrace();
}
Simplest way to consume Restful web services is using Spring RestTemplate.
http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/web/client/RestTemplate.html
Related
I need to create a service on the server-side for sending HTTP requests. It works like this:
1. Client sends a request to the server
2. Server uses singleton service for calling 3rd-party API via HTTP.
3. API returns the response
4. Server process this response and return it to the client
It is a synchronized process.
I created service:
public class ApacheHttpClient {
private final static CloseableHttpClient client = HttpClients.createDefault();
public String sendPost(String serverUrl, String body) {
try {
HttpPost httpPost = new HttpPost(serverUrl);
httpPost.setEntity(new StringEntity(body));
CloseableHttpResponse response = client.execute(httpPost);
String responseAsString = EntityUtils.toString(response.getEntity());
response.close();
return responseAsString;
} catch (IOException e) {
throw new RestException(e);
}
}
ApacheHttpClient is a singleton in my system. CloseableHttpClient client is a singleton too.
Question 1: Is it correct to use one instance of CloseableHttpClient client or I should create a new instance for each request?
Question 2: When I should close the client?
Question 3: This client can process only 2 connections in one time period. Should I use an executor?
The use of HttpClient instance as a singleton per distinct HTTP service is correct and is in line with the Apache HttpClient best practices. It should not be static, though.
http://hc.apache.org/httpcomponents-client-5.1.x/migration-guide/preparation.html
One should close HttpClient when releasing the HTTP service. In your case ApacheHttpClient should implement Closeable and close the internal instance of CloseableHttpClient in its #close method.
You probably should not, but it really depends on how exactly your application deals with request execution.
I am attempting to modify items in a Sharepoint list using the Sharepoint REST API from back-end java code. I am using NTLM authentication to access the server and Apache httpclient to perform the http requests. I am able to perform a GET request to the list URL without issue, but when doing a POST request, I am receiving an error:
The type SP.ListItemEntityCollection does not support HTTP PATCH
method
Here is the relevant code for the POST request:
JsonObject type = new JsonObject();
type.addProperty("type", "SP.Data.MyListListItem");
JsonObject listJson2 = new JsonObject();
listJson2.add("__metadata", type);
listJson2.addProperty("Title", "test");
String backToString = listJson2.toString();
CloseableHttpClient httpClient2 = HttpClients.createDefault();
HttpPost httpPost2 = new HttpPost(LIST_URL);
httpPost2.setEntity(new StringEntity(backToString));
httpPost2.addHeader("X-RequestDigest", formDigestValue);
httpPost2.addHeader("Content-Type", "application/json;odata=verbose");
httpPost2.addHeader("Accept", "application/json;odata=verbose");
httpPost2.addHeader("X-HTTP-Method", "MERGE");
httpPost2.addHeader("IF_MATCH", "*");
CloseableHttpResponse response2 = httpClient2.execute(httpPost2, context);
Am I doing something wrong here? I am following the post request from https://dev.office.com/sharepoint/docs/sp-add-ins/working-with-lists-and-list-items-with-rest.
I need to send an ID to the server and have the server to delete one record in a DB.
I want to use the HttpDelete Apache Android SDK integrated class but I cannot figure out how to use it and how to pass parameters to the server.
With the POST request I use .setEntity method on the HttpPost class.
But in HttpDelete there's no .setEntity method.
What I have so far achieved is:
HttpClient httpclient = new DefaultHttpClient();
HttpDelete httpdelete = new HttpDelete(url);
httpdelete.setHeader(HTTP.CONTENT_TYPE, "text/xml");
response = httpclient.execute(httpdelete);
HTTP DELETE requests do not have a body. You pass parameters right on the URL:
String url = "http://foo.com/bar?bing=bang"
HttpDelete httpdelete = new HttpDelete(url);
I have two web applications in two different server.I want send some data in header or request to other web application.How can I do that, please help me.
You can pass data by many means:
by making http request from your app:
URLConnection conn = new URL("your other web app servlet url").openConnection();
// pass data using conn. Then on other side you can have a servlet that will receive these calls.
By using JMS for asynchronous communication.
By using webservice (SOAP or REST)
By using RMI
By sharing database between the apps. So one writes to a table and the other reads from that table
By sharing file system file(s)...one writes to a file the other reads from a file.
You can use socket connection.
HttpClient can help
http://hc.apache.org/index.html
Apache HttpComponents
The Apache HttpComponents™ project is responsible for creating and
maintaining a toolset of low level Java components focused on HTTP and
associated protocols.
One web application is functioning as the client of the other. You can use the org.apache.http library to create your HTTP client code in Java. How you will do this depends on a couple of things:
Are you using http or https?
Does the application you are sending data to have a REST API?
Do you have a SOAP based web service?
If you have a SOAP based web service, then creating a Java client for it is very easy. If not, you could do something like this and test the code in a regular Java client before trying to run it in the web application.
import org.apache.http.client.utils.*;
import org.apache.http.*;
import org.apache.http.impl.client.*;
HttpClient httpclient = new DefaultHttpClient();
try {
URIBuilder builder = new URIBuilder();
builder.setHost("yoursite.com").setPath(/appath/rsc/);
builder.addParameter("user", username);
builder.addParameter("param1", "SomeData-sentAsParameter");
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
HttpResponse response = httpclient.execute(httpget);
System.out.println(response.getStatusLine().toString());
if (response.getStatusLine().getStatusCode() == 200) {
String responseText = EntityUtils.toString(response.getEntity());
httpclient.getConnectionManager().shutdown();
} else {
log(Level.SEVERE, "Server returned HTTP code "
+ response.getStatusLine().getStatusCode());
}
} catch (java.net.URISyntaxException bad) {
System.out.println("URI construction error: " + bad.toString());
}
I need to coding an Http Client using java which interact with a stateful http server. The client needs to
navigate to login page and accept cookies
submit login page with http form field filled
select goods and add to shopping cart
submit shopping cart
I am trying to use HttpClient to implement this client. However I found even I submitted the login form, it still return the login form just like my submit is invalid. Here is my code:
HttpClient agent = new DefaultHttpClient();
agent.getParams().setParameter(ClientPNames.COOKIE_POLICY,
CookiePolicy.RFC_2965);
CookieStore cookieStore = new BasicCookieStore();
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet httpget = new HttpGet(site);
HttpResponse response = agent.execute(httpget, localContext);
HttpEntity entity = response.getEntity();
entity.getContent().close();
HttpPost post = new HttpPost(site + "/login.aspx");
post.getParams().setParameter("LoginControl1$ctlLoginName", "myusername");
post.getParams().setParameter("LoginControl1$ctlPassword", "mypassword");
response = agent.execute(post, localContext);
entity = response.getEntity();
String s = IO.readContentAsString(entity.getContent());
System.out.println(s);
Any idea where I am wrong? Or do you have better way to implement this?
Thanks a lot
Green
Not really sure what might be wrong, but have you considered using tcpdump/Wireshark to grab the raw HTTP conversation with the server and compare what you're sending/receiving in HTTPClient with what you send/receive in your web browser when you submit the form?