Spring java object send and receive - java

I need to send Java object from client to Spring controller. I've tried the following. But not working.
My bean class - I have the same package and class in both client and service
public class DataObj implements Serializable {
private String stringData;
private byte[] byteData;
public String getStringData() {
return stringData;
}
public void setStringData(String stringData) {
this.stringData = stringData;
}
public byte[] getByteData() {
return byteData;
}
public void setByteData(byte[] byteData) {
this.byteData = byteData;
}
}
My controller
#RequestMapping(value = "/an/data", method = RequestMethod.POST)
public void subscribeUser(#RequestBody DataObj subscription){
System.out.println("DD");
bytes = subscription.getByteData();
}
My Client - Apache
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httppost = new HttpPost("http://localhost:8080/contex/an/data");
httppost.setEntity(new SerializableEntity((Serializable) dataObj , false));
httpClient.execute(httppost);
My Client - URLConnection
URL url = new URL("http://localhost:8080/contex/an/data");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
ObjectOutputStream writer = new ObjectOutputStream (conn.getOutputStream());
writer.writeObject(dataObj );
writer.flush();
conn.connect();
writer.close();
System.out.println(conn.getResponseCode());
Both the execution is not working. The controller trying to redirect to access denied page. Correct me, if my understanding is wrong, pardon me, if it is duplicate. JSON wrapping won't help me, since the java object having byte array. So please note that.
UPDATE
I'm receiving the following log
org.apache.tomcat.util.http.Parameters processParameters
INFO: Character decoding failed. Parameter...... [Showing my bean class package and the data in non readable format]

Finally I found the answer, always Servlets are like King. I used the following to make it work
#Autowired
private HttpServletRequest context;
#RequestMapping(value = "/an/data", method = RequestMethod.POST)
#ResponseBody
public String send() {
System.out.println("EEE");
try{
ObjectInputStream obj = new ObjectInputStream(context.getInputStream());
DataObj v = (DataObj )obj.readObject();
System.out.println(v.getStringData());
}catch(Exception e){
e.printStackTrace();
}
return "CAME";
}

Related

Should I use HttpURLConnection or RestTemplate [duplicate]

This question already has an answer here:
RestTemplate vs Apache Http Client for production code in spring project
(1 answer)
Closed 4 years ago.
Should I use HttpURLConnection in a Spring Project Or better to use RestTemplate ?
In other words, When it is better to use each ?
The HttpURLConnection and RestTemplate are different kind of beasts. They operate on different abstraction levels.
The RestTemplate helps to consume REST api and the HttpURLConnection works with HTTP protocol.
You're asking what is better to use. The answer depends on what you're trying to achieve:
If you need to consume REST api then stick with RestTemplate
If you need to work with http protocol then use HttpURLConnection, OkHttpClient, Apache's HttpClient, or if you're using Java 11 you can try its HttpClient.
Moreover the RestTemplate uses HttpUrlConnection/OkHttpClient/... to do its work (see ClientHttpRequestFactory, SimpleClientHttpRequestFactory, OkHttp3ClientHttpRequestFactory
Why you should not use HttpURLConnection?
It's better to show some code:
In examples below JSONPlaceholder used
Let's GET a post:
public static void main(String[] args) {
URL url;
try {
url = new URL("https://jsonplaceholder.typicode.com/posts/1");
} catch (MalformedURLException e) {
// Deal with it.
throw new RuntimeException(e);
}
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
try (InputStream inputStream = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(isr)) {
// Wrap, wrap, wrap
StringBuilder response = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
}
// Here is the response body
System.out.println(response.toString());
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
Now let's POST a post something:
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type", "application/json; charset=UTF-8");
try (OutputStream os = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter wr = new BufferedWriter(osw)) {
wr.write("{\"title\":\"foo\", \"body\": \"bar\", \"userId\": 1}");
}
If the response needed:
try (InputStream inputStream = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(isr)) {
// Wrap, wrap, wrap
StringBuilder response = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
}
System.out.println(response.toString());
}
As you can see the api provided by the HttpURLConnection is ascetic.
You always have to deal with "low-level" InputStream, Reader, OutputStream, Writer, but fortunately there are alternatives.
The OkHttpClient
The OkHttpClient reduces the pain:
GETting a post:
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url("https://jsonplaceholder.typicode.com/posts/1")
.build();
Call call = okHttpClient.newCall(request);
try (Response response = call.execute();
ResponseBody body = response.body()) {
String string = body.string();
System.out.println(string);
} catch (IOException e) {
throw new RuntimeException(e);
}
POSTing a post:
Request request = new Request.Builder()
.post(RequestBody.create(MediaType.parse("application/json; charset=UTF-8"),
"{\"title\":\"foo\", \"body\": \"bar\", \"userId\": 1}"))
.url("https://jsonplaceholder.typicode.com/posts")
.build();
Call call = okHttpClient.newCall(request);
try (Response response = call.execute();
ResponseBody body = response.body()) {
String string = body.string();
System.out.println(string);
} catch (IOException e) {
throw new RuntimeException(e);
}
Much easier, right?
Java 11's HttpClient
GETting the posts:
HttpClient httpClient = HttpClient.newHttpClient();
HttpResponse<String> response = httpClient.send(HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
.GET()
.build(), HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
POSTing a post:
HttpResponse<String> response = httpClient.send(HttpRequest.newBuilder()
.header("Content-Type", "application/json; charset=UTF-8")
.uri(URI.create("https://jsonplaceholder.typicode.com/posts"))
.POST(HttpRequest.BodyPublishers.ofString("{\"title\":\"foo\", \"body\": \"barzz\", \"userId\": 2}"))
.build(), HttpResponse.BodyHandlers.ofString());
The RestTemplate
According to its javadoc:
Synchronous client to perform HTTP requests, exposing a simple, template method API over underlying HTTP client libraries such as the JDK {#code HttpURLConnection}, Apache HttpComponents, and others.
Lets do the same
Firstly for convenience the Post class is created. (When the RestTemplate will read the response it will transform it to a Post using HttpMessageConverter)
public static class Post {
public long userId;
public long id;
public String title;
public String body;
#Override
public String toString() {
return new ReflectionToStringBuilder(this)
.toString();
}
}
GETting a post.
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Post> entity = restTemplate.getForEntity("https://jsonplaceholder.typicode.com/posts/1", Post.class);
Post post = entity.getBody();
System.out.println(post);
POSTing a post:
public static class PostRequest {
public String body;
public String title;
public long userId;
}
public static class CreatedPost {
public String body;
public String title;
public long userId;
public long id;
#Override
public String toString() {
return new ReflectionToStringBuilder(this)
.toString();
}
}
public static void main(String[] args) {
PostRequest postRequest = new PostRequest();
postRequest.body = "bar";
postRequest.title = "foo";
postRequest.userId = 11;
RestTemplate restTemplate = new RestTemplate();
CreatedPost createdPost = restTemplate.postForObject("https://jsonplaceholder.typicode.com/posts/", postRequest, CreatedPost.class);
System.out.println(createdPost);
}
So to answer your question:
When it is better to use each ?
Need to consume REST api? Use RestTemplate
Need to work with http? Use some HttpClient.
Also worth mentioning:
Retrofit
Intro to Feign
Declarative REST client

How to call `POST` RESTfull methods in Android?

I have developed a web service in Java. Below is a method of it.
#Path("/setup")
public class SetupJSONService {
#POST
#Path("/insertSetup")
#Consumes(MediaType.APPLICATION_JSON)
public String insertSetup(SetupBean bean)
{
System.out.println("Printed");
SetupInterface setupInterface = new SetupImpl();
String insertSetup = setupInterface.insertSetup(bean);
return insertSetup;
}
}
Below is how I call this method using Java Jersey in my computer.
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8080/TestApp/rest/setup").path("/insertSetup");
SetupBean setupBean = new SetupBean();
setupBean.setIdPatient(1);
setupBean.setCircleType(1);
target.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(setupBean, MediaType.APPLICATION_JSON_TYPE));
However, Now this method should be called in Android as well, but I'm not sure how to do that. I know how to make GET calls in android like below.
public static String httpGet(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn =
(HttpURLConnection) url.openConnection();
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
// Buffer the result into a string
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}
But since my method is POST and since it accept a Java Bean and it does return a String, how can I handle this in Android? Not interested using Jersey in android as it does have bad comments in Android environment.
Android provides a way to do what you want, but this is not a productive way, i like to use retrofit 2 to power my development and to write a better code.
Here a example of retrofit 2 that can help you =) :
add to your dependencies in build.gradle
dependencies {
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
}
Create your retrofit builder that specifies a converter and a base url.
public static final String URL = "http://localhost:8080/TestApp/rest/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Now create a Interface that will encapsulate your rest methods like below
public interface YourEndpoints {
#POST("setup/insertSetup")
Call<ResponseBody> insertSetup(#Body SetupBean setupBean);
}
Associate your endpoints interface with your retrofit instance.
YourEndpoints request = retrofit.create(YourEndpoints.class);
Call<ResponseBody> yourResult = request.insertSetup(YourSetupBeanObject);
yourResult.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//response.code()
//your string response response.body().string()
}
#Override
public void onFailure(Throwable t) {
//do what you have to do if it return a error
}
});
Ref to this links for more information:
http://square.github.io/retrofit/
https://github.com/codepath/android_guides/wiki/Consuming-APIs-with-Retrofit
that`s the code for the normal way you want
InputStream is = null;
OutputStream os = null;
HttpURLConnection con = null;
try {
//constants
URL url = new URL("http://localhost:8080/TestApp/rest/");
//Map your object to JSONObject and convert it to a json string
String message = new JSONObject().toString();
con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(1000);
con.setConnectTimeout(15000);
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setFixedLengthStreamingMode(message.getBytes().length);
con.setRequestProperty("Content-Type", "application/json;charset=utf-8");
//open
con.connect();
//setup send
os = new BufferedOutputStream(con.getOutputStream());
os.write(message.getBytes());
//clean up
os.flush();
//do somehting with response
is = con.getInputStream();
String contentAsString = readData(is,len);
os.close();
is.close();
con.disconnect();
} catch (Exception e){
try {
os.close();
is.close();
con.disconnect();
} catch (IOException e1) {
e1.printStackTrace();
}
}

Posting multipart form data via Android AsyncTask

My issue is with the writeArgsToConn() function.....i think. I cant figure out how to implement it.
I am trying to post multipart-formdata from an Android device using AsyncTask class. Can anyone help with this? I want to stay away from the depreciated org.apache.http.legacy stuff and stick with up-to-date Android libraries.
I was able to use similar implementation for a class called DoPostJSON which used Content-Type: application/json and that class works fine.
Same question but on Reddit: https://redd.it/49qqyq
I had issues with getting nodejs express server to detect the parameters being sent in. My DoPostJSON class worked fine and my nodejs server was able to detect parameters...for some reason DoPostMultiPart doesnt work and nodejs server cant see paramters being passed in. I feel like I am using the library the wrong way.
public class DoPostMultiPart extends AsyncTask<JSONObject, Void, JSONObject> implements Post{
#Override
public HttpURLConnection createConn(String action) throws Exception{
URL url = new URL(Utils.host_api + action);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Cache-Control", "no-cache");
conn.setReadTimeout(35000);
conn.setConnectTimeout(35000);
return conn;
}
#Override
public JSONObject getResponse(HttpURLConnection conn) throws Exception {
int responseCode = conn.getResponseCode();
String response = "";
if (responseCode == HttpsURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(in));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null)
stringBuilder.append(line).append("\n");
responseStreamReader.close();
response = stringBuilder.toString();
} else {
throw new Exception("response code: " + responseCode);
}
conn.disconnect();
return new JSONObject(response);
}
// TODO: fix this function
#Override
public void writeArgsToConn(JSONObject args, HttpURLConnection conn) throws Exception {
// define paramaters
String fullname = args.getString("fullname");
String email = args.getString("email");
String password = args.getString("password");
String confpassword = args.getString("confpassword");
Bitmap pic = (Bitmap) args.get("pic");
// plugin paramters into request
OutputStream os = conn.getOutputStream();
// how do I plugin the String paramters???
pic.compress(Bitmap.CompressFormat.JPEG, 100, os); // is this right???
os.flush();
os.close();
}
#Override
protected JSONObject doInBackground(JSONObject... params) {
JSONObject args = params[0];
try {
String action = args.getString("action");
HttpURLConnection conn = createConn(action);
writeArgsToConn(args, conn);
return getResponse(conn);
} catch (Exception e) {
Utils.logStackTrace(e);
return null;
}
}
}
I solved my issue by using OkHttpClient library.
JSONObject args = params[0];
try
{
final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart("fullname", args.getString("fullname"))
.addFormDataPart("email", args.getString("email"))
.addFormDataPart("password", args.getString("password"))
.addFormDataPart("confpassword", args.getString("confpassword"))
.addFormDataPart("pic", "profile.png", RequestBody.create(MEDIA_TYPE_PNG, (File) args.get("pic")))
.build();
Request request = new Request.Builder()
.url(Utils.host_api + args.getString("action"))
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
return new JSONObject(response.body().string());
}
catch (Exception e)
{
Utils.logStackTrace(e);
return null;
}

Invoking servlet from java main method

import java.net.*;
import java.io.*;
public class sample
{
public static void main (String args[])
{
String line;
try
{
URL url = new URL( "http://localhost:8080/WeighPro/CommPortSample" );
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
line = in.readLine();
System.out.println( line );
in.close();
}
catch (Exception e)
{
System.out.println("Hello Project::"+e.getMessage());
}
}
}
My Servlet is invoking another Jsp page like the below,
RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
I am not getting any reaction/output in the browser, where the servlet has to be executed once it is invoked.
Am I missing any basic step for this process? Please Help!!!
If you want to open it in browser try this
java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://localhost:8080/WeighPro/CommPortSample"));
You question is not clear. Do you actually want to invoke a Servlet from the Main method, or do you want to make an HTTP request to your web application?
If you want to make an HTTP request, I can't see any obvious problems with your code above, which makes me believe that the problem is in the Servlet. You also mention that you don't get anything in the browser, but running your program above does not involve a browser.
Do you mean that you don't get a response when you go to
http://localhost:8080/WeighPro/CommPortSample
in a browser?
As Suresh says, you cannot call a Servlet directly from a main method.
Your Servlet should instead call methods on other classes, and those other classes should be callable from the main method, or from Test Cases. You need to architect your application to make that possible.
import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class OutBoundSimul {
public static void main(String[] args) {
sendReq();
}
public static void sendReq() {
String urlString = "http://ip:port/applicationname/servletname";
String respXml = text;
URL url = null;
HttpURLConnection urlConnection = null;
OutputStreamWriter out = null;
BufferedInputStream inputStream = null;
try {
System.out.println("URL:"+urlString);
url = new URL(urlString);
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
System.out.println("SendindData");
out = new OutputStreamWriter(urlConnection.getOutputStream());
System.out.println("Out:"+out);
out.write(respXml);
out.flush();
inputStream = new BufferedInputStream(urlConnection.getInputStream());
int character = -1;
StringBuffer sb = new StringBuffer();
while ((character = inputStream.read()) != -1) {
sb.append((char) character);
}
System.out.println("Resp:"+sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Invoking Servlet with query parameters Form Main method
Java IO
public static String accessResource_JAVA_IO(String httpMethod, String targetURL, String urlParameters) {
HttpURLConnection con = null;
BufferedReader responseStream = null;
try {
if (httpMethod.equalsIgnoreCase("GET")) {
URL url = new URL( targetURL+"?"+urlParameters );
responseStream = new BufferedReader(new InputStreamReader( url.openStream() ));
}else if (httpMethod.equalsIgnoreCase("POST")) {
con = (HttpURLConnection) new URL(targetURL).openConnection();
// inform the connection that we will send output and accept input
con.setDoInput(true); con.setDoOutput(true); con.setRequestMethod("POST");
con.setUseCaches(false); // Don't use a cached version of URL connection.
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
con.setRequestProperty("Content-Language", "en-US");
DataOutputStream requestStream = new DataOutputStream ( con.getOutputStream() );
requestStream.writeBytes(urlParameters);
requestStream.close();
responseStream = new BufferedReader(new InputStreamReader( con.getInputStream(), "UTF-8" ));
}
StringBuilder response = new StringBuilder(); // or StringBuffer if not Java 5+
String line;
while((line = responseStream.readLine()) != null) {
response.append(line).append('\r');
}
responseStream.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace(); return null;
} finally {
if(con != null) con.disconnect();
}
}
Apache Commons using commons-~.jar
{httpclient, logging}
public static String accessResource_Appache_commons(String url){
String response_String = null;
HttpClient client = new HttpClient();
GetMethod method = new GetMethod( url );
// PostMethod method = new PostMethod( url );
method.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
method.setQueryString(new NameValuePair[] {
new NameValuePair("param1","value1"),
new NameValuePair("param2","value2")
}); //The pairs are encoded as UTF-8 characters.
try{
int statusCode = client.executeMethod(method);
System.out.println("Status Code = "+statusCode);
//Get data as a String OR BYTE array method.getResponseBody()
response_String = method.getResponseBodyAsString();
method.releaseConnection();
} catch(IOException e) {
e.printStackTrace();
}
return response_String;
}
Apache using httpclient.jar
public static String accessResource_Appache(String url) throws ClientProtocolException, IOException{
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
URIBuilder builder = new URIBuilder( url )
.addParameter("param1", "appache1")
.addParameter("param2", "appache2");
HttpGet method = new HttpGet( builder.build() );
// HttpPost method = new HttpPost( builder.build() );
// Create a custom response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
#Override
public String handleResponse( final HttpResponse response) throws IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
}
return "";
}
};
return httpclient.execute( method, responseHandler );
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
JERSY using JARS {client, core, server}
public static String accessResource_JERSY( String url ){
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource( url );
ClientResponse response = service.accept(MediaType.TEXT_PLAIN).get(ClientResponse.class);
if (response.getStatus() != 200) {
System.out.println("GET request failed >> "+ response.getStatus());
}else{
String str = response.getEntity(String.class);
if(str != null && !str.equalsIgnoreCase("null") && !"".equals(str)){
return str;
}
}
return "";
}
Java Main method
public static void main(String[] args) throws IOException {
String targetURL = "http://localhost:8080/ServletApplication/sample";
String urlParameters = "param1=value11&param2=value12";
String response = "";
// java.awt.Desktop.getDesktop().browse(java.net.URI.create( targetURL+"?"+urlParameters ));
// response = accessResource_JAVA_IO( "POST", targetURL, urlParameters );
// response = accessResource_Appache_commons( targetURL );
// response = accessResource_Appache( targetURL );
response = accessResource_JERSY( targetURL+"?"+urlParameters );
System.out.println("Response:"+response);
}
Simply you cannot do that.
A response and request pair will generated by web container. You cannot generate a response object and send to the browser.
By the way which client/browser you are expecting to get the response ? No idea. Right ?
When container receives a request from client then it generates response object and serves you can access that response in service method.
If you want to see/test the response, you have to request from there.

consuming SOAP web service in java

I am looking for some alternatives of consuming a SOAP web service in java. I am currently using a stub method to consume it and it's too simple for my instructor needs. My instructor said to do a trivial client, what was that suppose to mean?
SOAP is basically the submission of XML to a web server using the POST method. While the XML can get verbose, you should be able to construct the XML using StringBuilder and then use a simple HTTP client, like the Apache HttpClient to construct a POST request to a URL using
the XML string as the body.
That's about as simple as they come.
Here is the simple and lightweight example for consuming the soap api. Steps are below.
You must create the SOAPTestController.java, KflConstants.java And SoapClient.java class.
Then Implement the below code blocks and enjoy it.
Here is the SOAPTestController.java class
#Controller
public class SOAPTestController {
#RequestMapping(value = "/showdate", method = RequestMethod.GET)
public #ResponseBody String getDateAndTime() {
String DateAndTimeSOAPRequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"
+ "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\r\n"
+ " <soap12:Body>\r\n" + " <GetDateAndTime xmlns=\"http://tempuri.org/\" />\r\n"
+ " </soap12:Body>\r\n" + "</soap12:Envelope>";
String Fundtion = "GetDateAndTime";
return new SoapClient().ConsumeTheService(DateAndTimeSOAPRequest, "GetDateAndTime");
}
}
This is the KflConstants.java class
public class KflConstants {
public static final String SERVER_IP = "http://192.168.0.222/";
public static final String SERVICE_URL = SERVER_IP + "businesswebserviceNew/service.asmx";
public static final String CONTENT_TYPE_TEXT_XML = "text/xml; charset=utf-8";
public static final String GET_DATE_AND_TIME_URL = SERVICE_URL + "/GetDateAndTime";
}
Here is the SOAPClient.java class
public class SoapClient {
private static Logger log = LogManager.getLogger(SoapClient.class);
/*Input Stream Convert to the String Object*/
public static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
public String ConsumeTheService(String SOAPXML, String APINAME) {
String Result = null;
try {
/*Create The Connection*/
URL url = new URL(KflConstants.SERVICE_URL);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", KflConstants.CONTENT_TYPE_TEXT_XML);
conn.setRequestProperty(APINAME, KflConstants.GET_DATE_AND_TIME_URL);
log.info("Sending the envelope to server");
/*Send the request XML*/
OutputStream outputStream = conn.getOutputStream();
outputStream.write(SOAPXML.getBytes());
outputStream.close();
/* Read the response XML*/
log.info("Reading the Response");
InputStream inputStream = conn.getInputStream();
Result = convertStreamToString(inputStream);
inputStream.close();
/*INput Stream Convert to the SOAP Message*/
InputStream is = new ByteArrayInputStream(Result.getBytes());
SOAPMessage resposeSOAP = MessageFactory.newInstance().createMessage(null, is);
/*Return Values*/
log.info("Result SOAP:"+resposeSOAP.toString());
log.info("Result String:"+Result);
return Result;
} catch (Exception e) {
e.printStackTrace();
log.error(e);
return e.toString();
}
}
Thanks,
SoapRequestBuilder s = new SoapRequestBuilder();
s.Server = "127.0.0.1"; // server ip address or name
s.MethodName = "ConcatWithSpace";
s.XmlNamespace = "http://tempuri.org/";
s.WebServicePath = "/SimpleService/Service1.asmx";
s.SoapAction = s.XmlNamespace+s.MethodName;
s.AddParameter("one", "David");
s.AddParameter("two", "Hobbs");
String response = s.sendRequest();

Categories

Resources