How to use a webservice in java? - java

Well, I'm totally noob with this, I have all the code to parse the xml of solicitude and response, and the url to send it, but I don't have any idea about how to send it and how to receive the response. I can't find any complete guide or something. Thanks in advance, sorry for my bad english.

public class HttpURLConnectionExample {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
HttpURLConnectionExample http = new HttpURLConnectionExample();
System.out.println("Testing 1 - Send Http GET request");
http.sendGet();
System.out.println("\nTesting 2 - Send Http POST request");
http.sendPost();
}
// HTTP GET request
private void sendGet() throws Exception {
String url = "http://www.google.com/search?q=mkyong";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "https://selfsolve.apple.com/wcResults.do";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
}

The best solution was use SOAPConnectionFactory
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection connection = soapConnectionFactory.createConnection();
java.net.URL endpoint = new URL("url");
SOAPMessage message = xmlStringParser.getSoapMessageFromString(XMLString);
SOAPMessage response = connection.call(message, endpoint);
Thanks to all! :D

Related

HttpsURLConnection - Send POST request

I want to send a POST request to this particular API: https://developer.lufthansa.com/docs/read/api_basics/Getting_Started and I researched how to do that and tried everything but it simply doesn't work, I always get an HTTP 400 or an HTTP 401 error. Here's my code:
private void setAccessToken(String clientID, String clientSecret) {
try {
URL url = new URL(URL_BASE + "oauth/token");
String params = "client_id=" + clientID + "&client_secret=" + clientSecret + "&grant_type=client_credentials";
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
osw.write(params);
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
} catch(IOException e) {
e.printStackTrace();
}
}
Kenta1561
Seems that your code is working well and it may be the case that you are providing invalid clientID or clientSecret so that your are getting wrong response in this case (as 401 indicates unauthorized). One thing you can do is you are only getting the response message if the http request status is ok (200). You may also get the invalid response message in case of 400 or 401 http response status. In order to print the invalid response messages you may follow the code below:
private void setAccessToken(String clientID, String clientSecret) throws Exception {
String params = "client_id=" + clientID + "&client_secret=" + clientSecret + "&grant_type=client_credentials";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
BufferedReader in;
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
if (responseCode >= 400)
in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
else
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
In this way you can also get invalid response message. In your case when I tried to hit the provided api it is giving me the response below:
{"error": "invalid_client"}

Login to another application after post request Spring JAVA

I write this controller and the main idia is that i want to login in another my web application using Post REQUEST. I tested it and the response is 200 OK ! but the controller only redirects me without log me in the another application. Please help.
#Controller
public class BackdoorLoginController {
private final String USER_AGENT = "Mozilla/5.0";
#RequestMapping(value = "/loginTo", method = RequestMethod.GET)
public void redirectWithUsingRedirectPrefix(HttpServletResponse res, HttpServletRequest request)
throws IOException, ServletException {
#SuppressWarnings("restriction")
URL url = new URL(null, "http://www.url.com", new sun.net.www.protocol.https.Handler());
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
String urlParameters = "submit=1&email=email#email.com&pass=password";
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("charset", "utf-8");
con.setRequestProperty("Host", "http://www.url.com");
con.setUseCaches(false);
con.setDoOutput(true);
con.setRequestProperty("Content-Length", Integer.toString(postDataLength));
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
try (DataOutputStream q = new DataOutputStream(con.getOutputStream())) {
q.write(postData);
}
// Send post request
// con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
res.sendRedirect("http://www.url.com");
}
}

While making post call i am getting below exception

Error description:
java.lang.NoSuchMethodError: org.apache.http.HttpHost.getAddress()Ljava/net/InetAddress;
at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:102)
Could anyone help me here....what i am missing ???
use below sample code :
// HTTP POST request
private void sendPost() throws Exception {
String url = "https://selfsolve.apple.com/wcResults.do";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=& num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
}

How to call SOAP web services from JAVA

I want to know that how we can call SOAP web services from GET and POST request from java program.
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class HttpURLConnectionExample{
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
HttpURLConnectionExample http = new HttpURLConnectionExample();
//System.out.println("Testing 1 - Send Http GET request");
//http.sendGet();
System.out.println("\nTesting 2 - Send Http POST request");
http.sendPost();
}
// HTTP GET request
private void sendGet() throws Exception {
String url = "http://http://localhost/getmiweb/public/api/v1/OrderAPI";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "http://http://localhost/getmiweb/public/api/v1/OrderAPI";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
//Passing Parameters
String urlParameters = "token=t0ocgQ/jj8YbjasuLYJ12KJoZmaLNt4zUcEZZKxCU6E=&orderId=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
}

HTTP Request through java getting 401 response

I am trying to invoke a url through java using java.net.HttpURLConnection.
Below is the code.
I get 401 as response. The url is up.
// HTTP GET request
private void sendGet() throws Exception {
String url = "http://10.10.200.151:8720/scheduler/stat.go?opt1=0&opt2=0&opt3=0";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
Is there something missing.
HTTP status 401 indicate that the request requires authentication.
Perhaps this url need login, and the server check this by your cookie.

Categories

Resources