Using java, when I expose some web service with Soap, I have a WSDL which describes all input/output, and if I use this WSDL in my SoapUI client, it will analyze it and generate some sample request for me.
What is the process to do this with Rest/Json. I know about wadl, but SoapUI can't generate sample request from this. I know about third party tools like Swagger suite, but is this the only way ? Do u have to use some external documentation tool to expose your API and show users some sample requests ?
There is no answer yet, so here is one a few years later.
You need to use OpenAPI Specification (let's call the result a "Swagger contract"), which defines a standard, language-agnostic interface to RESTful APIs and just forget about WADL.
This will be the equivalent of a SOAP WSDL, but easier to read , easier to produce, and lighter in constraints.
With Swagger, you can work in "Contract first" (using https://editor.swagger.io/ to design the contract) or in "Code first", where you will use frameworks like Springfox to generate the swagger contract from code + annotations. The last one is much easier imo, and it's just a different way of doing "contract first", it's not like if u were implementing the whole application before designing the contract.
Once you have the "swagger contract" document available on an URL, you can deploy a swagger-ui website to visualize it in an interactive way : it will generate some sample requests and will allow you to execute these requests after customizing them.
try {
url="put your service url";
HttpPost request = new HttpPost(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
// Build JSON string
JSONStringer item = new JSONStringer()
.object()
.key("password").value(pass)
.key("username").value(email)
.endObject();
StringEntity entity = new StringEntity(item.toString());
request.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity entity1 = response.getEntity();
InputStream stream = entity1.getContent();
r = Splash.convertStreamToString(stream);
JSONObject jo = new JSONObject(r);
s= (Integer) jo.get("Flag");
Log.d("json result is:", r);
statusCode = response.getStatusLine().getStatusCode();
} catch (Exception e) {
e.printStackTrace();
Log.d("error", "code"+0);
}
return s;
}
Related
I have to call a web service located in http://ip:port/ws which has no wsdl.
I can send an HTTP POST using Spring framework's RestTemplate and get answer as raw input from the service. But this is annoying a bit, that's why I am looking for the correct way to consume this web service without WSDL.
Can anybody suggest a 'best practice' way for this task?
There is really no best practice, recreating the WSDL or at least the XML Schema seems like your only option to improve upon your current approach.
If you're really lucky, it'll return some consistent XML that you might be able to throw an XPath parser at to extract the bits you need. You might be able to tease out the XML schema either from the data it returns (look for a namespace declaration at the top of the document somewhere, and see if you can follow the URI it references), or drop the data into an on-line schema generator like this one
I could not find the best solution, and did some workaround. So as we know the SOAP call in HTTP environment is a standard HTTP POST with the soap envelope in HTTP POST body. So I did the same. I stored the xml soap requests in different place just not mess with the code:
public static final String REQ_GET_INFO = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:xyz\">" +
" <soapenv:Header/>" +
" <soapenv:Body>" +
" <urn:export>" +
" <cardholderID>%s</cardholderID>" +
" <bankId>dummy_bank</bankId>" +
" </urn:export>" +
" </soapenv:Body>" +
"</soapenv:Envelope>";
And in service layer I used RestTemplate post call with required headers:
#Value("${service.url}") // The address of SOAP Endpoint
private String wsUrl;
public OperationResponse getCustomerInfo(Card card) {
OperationResponse operationResponse = new OperationResponse(ResultCode.ERROR);
try {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "text/xml");
HttpEntity<String> request = new HttpEntity<>(String.format(Constants.SoapRequest.REQ_GET_INFO,
card.getCardholderId()), headers);
String result = restTemplate.postForObject(wsUrl, request, String.class);
if(!result.contains("<SOAP-ENV:Fault>")) {
// Do SOAP Envelope body parsing here
}
}
catch(Exception e) {
log.error(e.getMessage(), e);
}
return operationResponse;
}
A little bit of dirty job, but it worked for me :)
I am pretty new concerning REST api and POST request.
I have the url of a REST api. I need to access to this api by doing an API call in JAVA thanks to a client id and a client secret (I found a way to hash the client secret). However, as I am new I don't know how to do that api call. I did my research during this all day on internet but I found no tutorial, website or anything else about how to do an api call. So please, does anyone know a tutorial or how to do that? (if you also have something about POST request it would be great)
I would be very thankful.
Thank you very much for your kind attention.
Sassir
Here's a basic example snippet using JDK classes only. This might help you understand HTTP-based RESTful services a little better than using a client helper. The order in which you call these methods is crucial. If you have issues, add a comments with your issue and I will help you through it.
URL target = new URL("http://www.google.com");
HttpURLConnectionconn = (HttpURLConnection) target.openConnection();
conn.setRequestMethod("GET");
// used for POST and PUT, usually
// conn.setDoOutput(true);
// OutputStream toWriteTo = conn.getOutputStream();
conn.connect();
int responseCode = conn.getResponseCode();
try
{
InputStream response = conn.getInputStream();
}
catch (IOException e)
{
InputStream error = conn.getErrorStream();
}
You can also use RestTemplate from Spring: https://spring.io/blog/2009/03/27/rest-in-spring-3-resttemplate
Fast and simple solution without any boilerplate code.
Simple example:
RestTemplate rest = new RestTemplate();
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("firstParamater", "parameterValue");
map.add("secondParameter", "differentValue");
rest.postForObject("http://your-rest-api-url", map, String.class);
The Restlet framework also allows you to do such thing thanks to its class ClientResource. In the code below, you build and send a JSON content within the POST request:
ClientResource cr = new ClientResource("http://...");
SONObject jo = new JSONObject();
jo.add("entryOne", "...");
jo.add("entryTow", "...");
cr.post(new JsonRepresentation(jo), MediaType.APPLICATION_JSON);
Restlet allows to send any kind of content (JSON, XML, YAML, ...) and can also manage the bean / representation conversion for you using its converter feature (creation of the representation based on a bean - this answer gives you more details: XML & JSON web api : automatic mapping from POJOs?).
You can also note that HTTP provides an header Authorization that allows to provide authentication hints for a request. Several technologies are supported here: basic, oauth, ... This link could help you at this level: https://templth.wordpress.com/2015/01/05/implementing-authentication-with-tokens-for-restful-applications/.
Using authentication (basic authentication for example) can be done like this:
String username = (...)
String password = (...)
cr.setChallengeResponse(ChallengeScheme.HTTP_BASIC, username, password);
(...)
cr.post(new JsonRepresentation(jo), MediaType.APPLICATION_JSON);
Hope it helps you,
Thierry
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());
}
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
Sorry, I'm quite new to Java.
I've stumbled across HttpGet and HttpPost which seem to be perfect for my needs, but a little long winded. I have written a rather bad wrapper class, but does anyone know of where to get a better one?
Ideally, I'd be able to do
String response = fetchContent("http://url/", postdata);
where postdata is optional.
Thanks!
HttpClient sounds like what you want. You certainly can't do stuff like the above in one line, but it's a fully-fledged HTTP library that wraps up Get/Post requests (and the rest).
I would consider using the HttpClient library. From their documentation, you can generate a POST like this:
PostMethod post = new PostMethod("http://jakarata.apache.org/");
NameValuePair[] data = {
new NameValuePair("user", "joe"),
new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
// execute method and handle any error responses.
...
InputStream in = post.getResponseBodyAsStream();
// handle response.
There are a number of advanced options for configuring the client should you eventually required those.