Want to translate old Java soap.jar style code to something modern - java

I have some 10 year old Java code for calling a legacy SOAP authentication service. The WSDL is RPC:ENCODED and contains many typos. I was hoping to easily convert the old code to Axis 1.4 or something, but ran into snags. Everything I looked at wanted to use the WSDL. Can someone help translate this into modern code that doesn't require the faulty WSDL?
Here's the SOAP call section:
SOAPMappingRegistry soapmappingregistry = new SOAPMappingRegistry();
BeanSerializer beanserializer = new BeanSerializer();
soapmappingregistry.mapTypes(Constants.NS_URI_SOAP_ENC, new QName(
"urn:xml-soap-session-demo", "authenticationresult"),
AuthenticationResult.class, beanserializer, beanserializer);
Call call = new Call();
call.setSOAPMappingRegistry(soapmappingregistry);
call.setTargetObjectURI("urn:Security");
call.setMethodName("authenticate");
call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
Vector<Object> vector = new Vector<Object>();
vector.addElement(new Parameter("app", String.class, "PHS", null));
vector.addElement(new Parameter("user", String.class, userName, null));
vector.addElement(new Parameter("password", String.class, password, null));
vector.addElement(new Parameter("encryption", Integer.class, new Integer(0), null));
call.setParams(vector);
Response response = null;
URL endpointURL = new URL(endpoint);
response = call.invoke(endpointURL, "");
if (!response.generatedFault()) {
Parameter parameter = response.getReturnValue();
Object obj = parameter.getValue();
...
}
Many thanks.

Well, most soap frameworks relies on the WSDL standard a lot. Axis, CXF, Spring WS etc. I think you could try Spring WS. It has saved me a couple of times when you don't know or want to use the entire WSDL (but knows how the payload should be encoded).
However, why do you even want to port that thing if the service is full of type-o:s? Old client, old service - why don't you keep it that way and upgrade the code once the service has been replaced with something without type-o:s? I don't think you will end up with something less ugly anyway.

Related

How can I send a JSON body with AsyncHttpClient?

I'm using AsyncHttpClient library to make HTTP requests from a very basic Android app. For now, I just need to make a POST request with a JSON body (and that's a mandatory constraint, since the REST services I have to use expect a request in that format) containing a username and a password.
Not knowing much about Android development and the library in question I tried to make a simple GET request to Google, and it perfectly worked. Then, I tried to switch to a POST request but it seems from the documentation that the post method needs strictly a RequestParams parameter.
I really need to send a JSON: is there a way to do so with AsyncHttpClient? I tried several solutions found both on the web and on StackOverflow, but unfortunately no one worked.
Ultimately, as a last chance, I'm willing to switch library (and suggestions in this direction would be welcome, too - at least if they're easy-to-use as AsyncHttpClient is, considering my inexperience), but I would prefer to stick to my current choice.
Thanks for your help.
first, i suggest u to use retrofit library, it's simple, useful and sweet
but for now, we should to know that how do you do your post,
for example, do you test this:
private static AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("param1", "Test");
client.post(Url, params, responseHandler);
JSONObject jsonParams = new JSONObject();
jsonParams.put("param1", "Test");
StringEntity entity = new StringEntity(jsonParams.toString());
client.post(context, Url, entity, "application/json",responseHandler);

Rest api call and POST request (java)

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

Put request parameters not getting set

This may be standard stuff but unable to get it wokring.
I'm using org.apache.commons.httpclient.methods for making Http request from my Java code. In one instance I've to make a PUT request and pass some parameters. I'm doing it the following way:
PutMethod putMethod = new PutMethod(url);
putMethod.getParams().setParameter("param1", "param1Value");
putMethod.getParams().setParameter("param2", "param2Value");
httpClient.executeMethod(putMethod);
But at the server, when it tries to read these parameters - it can only get null.
However, When I modify my url as url?param1=param1Value&param2=param2Value it works.
How do I get it working using setParameter method?
To add Query Params to PutMethod, follow this method.
NameValuePair[] putParameters = new NameValuePair[2];
putParameters[0] = new NameValuePair(Param1, value1);
putParameters[1] = new NameValuePair(Param2, value2);
HttpClient client = new HttpClient();
PutMethod putMethod = new PutMethod(url);
putMethod.setQueryString(putParameters);
Then Call,
int response = client.executeMethod(putMethod);
Instead of putMethod.setQueryString(putParameters); you could also use
putMethod.setRequestBody(EncodingUtil.formUrlEncode(putParameters, "UTF-8"));
(This is deprecated)
GetMethod, PostMethod have slight differences when adding Query Params compared to the above code.
For More Code Examples : http://www.massapi.com/class/pu/PutMethod.html
Hope this helps.
your server side code has to support the PUT method
for example if its a Servlet you can include the method
doPUT(); // your put request will be delivered to this method
if you use REST based frameworks such as jersey
you can use
#PUT
Response yourPutMethod(){..}

How to make a SOAP call in Java

This seems like it should be simple, but maybe I'm missing something. I just want to make a SOAP call in Java, preferrably using only built-in APIs. I'm a little overwhelmed looking at javax.xml.soap package in the Java documentation. I have tried searching Google, but it seems like all the results are from 2000-2002, and they are all talking about libraries that can be used for SOAP calls (before SOAP libraries were built in, I guess).
I don't need to handle the SOAP request; only make one. This site has an example that is pretty simple, but it doesn't use the built-in Java SOAP libraries. How would I do basically the same thing using core Java?
// Create the parameters
Vector params = new Vector( );
params.addElement(
new Parameter("flightNumber", Integer.class, flightNumber, null));
params.addElement(
new Parameter("numSeats", Integer.class, numSeats, null));
params.addElement(
new Parameter("creditCardType", String.class, creditCardType, null));
params.addElement(
new Parameter("creditCardNumber", Long.class, creditCardNum, null));
// Create the Call object
Call call = new Call( );
call.setTargetObjectURI("urn:xmltoday-airline-tickets");
call.setMethodName("buyTickets");
call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
call.setParams(params);
// Invoke
Response res = call.invoke(new URL("http://rpc.middleearth.com"), "");
// Deal with the response
Soap has changed a lot since the early days. You can do things like what you describe, but it is not common.
A more common practice now is to use a wsdl2java tool to generate a client API from a WSDL description of the service. That will give you a nice, clean, API to call.
Apache CXF is one place to go for this sort of thing.
One proviso is rpc/encoded. If you are dealing with an old service, it might be rpc/encoded, and in that case your best bet is Apache Axis 1.x. Everything else has run away from rpc/encoded.
The simplest way is soap-ws library:
https://github.com/reficio/soap-ws
SoapClient client = SoapClient.builder()
.endpointUrl("http://rpc.middleearth.com")
.build();
client.post(envelope);

ksoap2 complex parameter

I need to call a web service using ksoap2, I have been doign this successfully up till the point where I need to pass a more complex type to the web service.
Does anybody have an example of passing a complex type to a webservice, preferably, only using SoapObject (the object in question is only Strings and dateTimes.
Thanks
in advance
Here is a working tutorial for complex types and arrays with KSOAP . Hope it helps.
Figured out how to do it. Simply used a SoapObject as a property.
I think you can use this android web service client open source tool.
Where you needn't use the soap Object or think with the soap envelop its just like call a method of a service.
say, for a service say ComplexReqService with param ComplexRequest you have to just write :
ComplexReqService service = new ComplexReqService();
CoplextReqPort port = service.getPort();
String resp = port.getResponse ( new ComplexRequest() );
In this way, It will support the complex response as well.

Categories