How can i made soap Request and Response in Java? - java

How can I execute the soap webservices and how can I print the data?
Currently I am using the following code
package com.appulento.pack;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class SimpleHTTPRequest
{
public static void main(String[] args) throws Exception {
final String url =
"http://**********:8000/sap/bc/srt/rfc/sap/zmaterials_details/" +
"800/zmaterials_details/zmaterials_details_bind",
soapAction ="urn:sap-com:document:sap:soap:functions:mc-style/ZMATERIALS_DETAILS",
envelope1="<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"" +
" xmlns:urn=\"urn:sap-com:document:sap:soap:functions:mc-style\">" +
"<soapenv:Header>"+
"<soapenv:Body>"+
"<urn:ZMATERIALS_DETAILS>"+
"<Language>D</Language>"+
"<MaterialGroup>00208</MaterialGroup>"+
"</urn:ZMATERIALS_DETAILS>"+
"</soap:Body>"+
"</soap:Envelope>" ;
HttpURLConnection connection = null;
try {
final URL serverAddress = new URL("http://*********:8000/sap/bc/srt/wsdl/"+
"srvc_14DAE9C8D79F1EE196F1FC6C6518A345/wsdl11/allinone/ws_policy/" +
"document?sap-client=800&sap-user=************&sap-password=****");
connection = (HttpURLConnection)serverAddress.openConnection();
connection.setRequestProperty("SOAPAction", soapAction);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.append(envelope1);
writer.close();
final BufferedReader rd =
new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = rd.readLine()) != null) System.out.println(line);
} finally { connection.disconnect(); }
}
}
I want send xml as input request and I want to display in xml too.

Iit's possible to sent HTTP request using httpConnection and parse response, like you do.
But it is already written by other people, use wsimport tool with -keep option. It will generate for you Java artifacts for sending request using SOAP.

Related

Minecraft auth server returning 403?

So I'm trying to make a custom launcher for my custom Minecraft client but I need a session id to launch the game. This is the code I'm using to try and get a session ID:
package net.arachnamc;
import org.json.JSONObject;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
public class Main {
public static void main(String[] args) throws IOException {
String AUTH_SERVER = "https://authserver.mojang.com/authenticate";
String json = String.format(
"{" +
"\"clientToken\":\"%s\"," +
"\"username\":\"%s\"," +
"\"password\":\"%s\"" +
"}",
UUID.randomUUID().toString(),
"Koolade446",
"MyPasswordCensored"
);
JSONObject jso = new JSONObject(json);
System.out.println(json);
URL url = new URL(AUTH_SERVER);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
OutputStream os = urlConnection.getOutputStream();
os.write(json.getBytes(StandardCharsets.UTF_8));
os.close();
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
urlConnection.disconnect();
}
}
However, the server returns a 403 forbidden every time. I use a Microsoft account but I can't find any documentation on how to authenticate a Microsoft account so I assumed this was it. Any help is appreciated.

HTTP request is full of junk

I've been working on simple http server in java. When I try to send some http request via google
browser "line" variable should have request string but it has junk characters.
Do you have any idea what is causing the problem?
Code is from this tutorial: https://www.youtube.com/watch?v=FqufxoA4m70&t=2061s&ab_channel=BloomInstituteofTechnology
Here is part of code where you can find this problem.
package com.company;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Main
{
public static void main(String[] args) throws Exception
{
try( ServerSocket socketServer = new ServerSocket(8080))
{
System.out.println("Server created");
while (true)
{
try (Socket client = socketServer.accept())
{
System.out.println("Client connected: " + client.toString());
InputStreamReader isr = new InputStreamReader(client.getInputStream());
BufferedReader br = new BufferedReader(isr);
StringBuilder request = new StringBuilder();
String line;
line = br.readLine();
while(!line.isBlank())
{
request.append(line);
line = br.readLine();
}
}
}
}
}
I don't know what you're actually doing with your browser. What are you typing in the URL bar? If you are trying to use https instead of http it will not work. Maybe "google browser" is tricking you and doing stuff behind your back... not exactly sending simple HTTP gets.
This works. It's not perfect but at least all IO streams are properly closed and a dummy response is sent to the client (which otherwise will remain hanging).
Try it by typing in your browser http://localhost:8080/some-random-url.
I cannot try with chrome as I don't use it, but this works using Firefox. As a rule, i would test stuff like this with curl and not with a browser - you have more control while testing simple stuff.
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) throws Exception {
try (ServerSocket socketServer = new ServerSocket(8080)) {
System.out.println("Server created");
while (true) {
try (Socket client = socketServer.accept()) {
System.out.println("Client connected: " + client.toString());
try (final InputStream is = client.getInputStream();
final InputStreamReader isr = new InputStreamReader(is);
final BufferedReader br = new BufferedReader(isr);
final OutputStream os = client.getOutputStream()) {
final StringBuilder request = new StringBuilder();
String line;
while (!(line = br.readLine()).isBlank()) {
request.append(line).append("\n");
}
System.out.println("+++++++++++++++++++++++ REQUEST ");
System.out.println(request);
String response = "HTTP/1.1 200 OK\r\n" +
"Content-Type: text/plain\r\n" +
"Connection: closed\r\n" +
"\r\n" +
"Hello there!\r\n";
os.write(response.getBytes(StandardCharsets.UTF_8));
os.flush();
System.out.println("----------------------- RESPONSE ");
System.out.println(response);
}
}
}
}
}
}
Random remark: don't implement an HTTP server on your own. Just do it to understand how it works.

Java and REST POST method - how to transform URL POST request to JSON Body POST Request?

I have class which works completely and sends POST request successfully toward the external system.
paramaters which are sent currently in the class are:
username:maxadmin
password:sm
DESCRIPTION: REST API test
Now I want to do copy paste of this class and transform it in that way so I could POST request using the JSON body but I am not sure how to do it.
I saw that I should probably have conn.setRequestProperty("Content-Type", "application/json"); instead of application/x-www-form-urlencoded
Can someone please transform my code in order to POST REQUEST using JSON body for parameters sending instead of URL?
This is my 'URL' working class (you will see username/password are in URL while parameters are send in array I have currently only one attribute DESCRIPTION which I am sending)
package com.getAsset;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.json.*;
public class GETAssetsPOST {
public static String httpPost(String urlStr, String[] paramName,
String[] paramVal) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
for (int i = 0; i < paramName.length; i++) {
writer.write(paramName[i]);
writer.write("=");
writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
writer.write("&");
}
writer.close();
out.close();
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();
}
public static void main(String[] args) throws Exception {
String[] attr = new String[1];
String[] value = new String[1];
attr[0] = "DESCRIPTION";
value[0] = "REST API test";
String description = httpPost("http://192.168.150.18/maxrest/rest/os/mxasset/123?_lid=maxadmin&_lpwd=sm",attr,value);
System.out.println("\n"+description);
}
}
Thank you

Getting 405 error when making a HTTP get request to a webservice

I'm making the HTTP GET request from a basic java program to a URL which happens to be "http://localhost:9992/users/john.doe#example.com":
public class Tester {
public static void main(String[] args) {
HttpRequester.doesUserExist("john.doe#example.com");
}
}
The implementation of the HTTPRequester is this:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpRequester {
private static HttpURLConnection connection = null;
public static boolean doesUserExist(final String email) {
final String targetUrl = Constants.URL_USER_SRVC + email;
System.out.println(targetUrl);
try {
URL url = new URL(targetUrl);
connection = (HttpURLConnection) url.openConnection();
System.out.println(connection.getRequestMethod());
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
connection.setUseCaches(false);
connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(
connection.getOutputStream());
outputStream.writeBytes(email);
outputStream.close();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer response = new StringBuffer();
String line;
while((line = reader.readLine()) != null) {
response.append(line);
response.append('\r');
}
reader.close();
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
The webservice embedded in a Grizzly server and here are the APIs:
#Path("/users")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public class UserResource {
#GET
public List<User> getUsers() {
return UserService.getUsers();
}
#GET
#Path("/{userEmail}")
public User getUser(#PathParam("userEmail") String userEmail) {
return UserService.getUser(userEmail);
}
}
Please take note that the webservice and java program are two separate projects. When I execute the main method I get this error output in the console:
java.io.IOException: Server returned HTTP response code: 405 for URL: http://localhost:9992/users/john.doe#example.com
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1627)
at com.axa.visualizr.auth.utils.HttpRequester.doesUserExist(HttpRequester.java:30)
at com.axa.visualizr.auth.core.Tester.main(Tester.java:8)
What I think is odd is that the error outputs this at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1627) even though I imported java.net.HttpURLConnection;. I have tried opening the declaration on that line but Eclipse states that it is not an valid line number in that class.
I don't know why it's saying that the method is not allowed when I have setRequestMethod("GET"). Maybe it might be because the java program is not running on any kind of server? The Tester.java is only for testing purposes eventually I will move HTTPRequester to another webservice and make the call from webservice A to webservice B.
Since you are passing something in the requestbody, java is interpreting it as a POST request. Please remove below lines from your code and try:
DataOutputStream outputStream = new DataOutputStream(
connection.getOutputStream());
outputStream.writeBytes(email);
outputStream.close();
Try below code:
final String targetUrl = Constants.URL_USER_SRVC + URLEncoder.encode(email, "UTF-8");
instead of: final String targetUrl = Constants.URL_USER_SRVC + email;

Java - Perform a http Request POST and GET on the same connection

I have something I am trying to achieve.
I have a web application running on my localhost on port 8080.
I have a HTTP Server running on localhost:9005.
I have a JSP form that passes info to a servlet java class, that in turn performs the HTTP post to the URL on the HTTP Server localhost:9010 with the data string.
What I need to do is perform the POST and GET as part of the same connection. I have them working as two separate calls, but not on the same connection. It needs to be the same connection, as I post data, the HTTP Server takes this data, processes it and outputs unique data to this URL. Therefore the GET needs to be part of the same connection as he POST.
Can anyone please help?
This is my Process Request java code:
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.List;
import java.util.Map.Entry;
public class ProcessRequest {
public void sendRequestToGateway() throws Throwable{
String message = URLEncoder.encode("OP1387927", "UTF-8");
try {
URL url = new URL("http://localhost:9005/json");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write("operator=" + message);
writer.close();
System.out.println("connection.getResponseCode() : " + connection.getResponseCode());
System.out.println("connection.getResponseMessage()" + connection.getResponseMessage());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
receiveMessageFromGateway();
} else {
// Server returned HTTP error code.
}
//receiveMessageFromGateway();
} catch (MalformedURLException e) {
// ...
} catch (IOException e) {
// ...
}
}
public void receiveMessageFromGateway() throws Throwable {
HttpURLConnection client = null;
OutputStreamWriter wr = null;
BufferedReader rd = null;
StringBuilder sb = null;
String line = null;
try {
URL url = new URL("http://localhost:9005/json");
client = (HttpURLConnection) url.openConnection();
client.setRequestMethod("GET");
client.setDoOutput(true);
client.setReadTimeout(10000);
client.connect();
System.out.println(" *** headers ***");
for (Entry<String, List<String>> headernew : client.getHeaderFields().entrySet()) {
System.out.println(headernew.getKey() + "=" + headernew.getValue());
}
System.out.println(" \n\n*** Body ***");
rd = new BufferedReader(new InputStreamReader(client.getInputStream()));
sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line + '\n');
}
System.out.println("body=" + sb.toString());
} finally {
client.disconnect();
rd = null;
sb = null;
wr = null;
}
}
}
Why don't you just return the result from the original POST?
In general you can't control connection reuse with HttpUrlConnection. You might be able to cast your connection to the specific implementation class and interfere with it but that's a horribly unstable way of doing it.
Apache HttpClient is probably a better option, given the requirements.
You can use Apache HTTP Client for this. Its very simple.
If you are using maven, just add the following lines into your POM file:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.3</version>
</dependency>
In this example, I'm submitting a POST request and after that a GET request.
Take a look:
public static String get(String p_url) throws IOException
{
CloseableHttpClient httpclient = HttpClients.createDefault();
// First request: POST
HttpPost httpPost = new HttpPost("http://the-api-url.com/Login/Auth&token=12345"));
CloseableHttpResponse response_post = httpclient.execute(httpPost);
System.out.println(response_post.getStatusLine());
HttpEntity entity_post = response_post.getEntity();
System.out.println(EntityUtils.toString(entity_post));
// Second request: GET
HttpGet httpGet = new HttpGet(p_url);
CloseableHttpResponse response_get = httpclient.execute(httpGet);
System.out.println(response_get.getStatusLine());
HttpEntity entity_get = response_get.getEntity();
System.out.println(EntityUtils.toString(entity_get));
response_post.close();
response_get.close();
return EntityUtils.toString(entity_get);
}

Categories