HTTP post request fails - java

I wrote the below code to send post request to an url. When I ran the code I am getting 500 error code. But, when I tried the same url in SOAP UI with the below headers I got the response back. May I know what is wrong in my code. Thanks in advance. I doubt I didn't add the headers properly.
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:arm="http://siebel.com/Webservice">
<soapenv:Header>
<UsernameToken xmlns="http://siebel.com/webservices">username</UsernameToken>
<PasswordText xmlns="http://siebel.com/webservices">password</PasswordText>
<SessionType xmlns="http://siebel.com/webservices">Stateless</SessionType>
</soapenv:Header>
<soapenv:Body>
<arm:QueryList_Input>
<arm:SRNum></arm:SRNum>
</arm:QueryList_Input>
</soapenv:Body>
</soapenv:Envelope>
Below is my code.
package com.siebel.Webservice;
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 HttpQueryList {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
HttpQueryList http = new HttpQueryList();
System.out.println("\nTesting 2 - Send Http POST request");
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "https://mywebsite.org/start.swe";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("UsernameToken", "username");
con.setRequestProperty("PasswordText", "password");
String urlParameters = "SWEExtSource=WebService&SWEExtCmd=Execute&WSSOAP=1";
// 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());
}
}

In your XML, you are specifying a token. When I have done this using SOAP UI, I have a certificate file that I use. In my case, I put it in my C:\Program Files (x86)\SmartBear\SoapUI-5.2.1\bin folder. Then I configured SOAP UI to use this. Do you have a certificate? If yes, are you referencing it?

Related

Received fatal alert: handshake_failure webservice

I have hired a web service that sends sms messages to mobile phone. I have tried to make the post request but I amb getting the error:
Exception in thread "main" javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
The webservice company gave me all the information needed for making the the url: the user, the password, the params needed, the response etc
The gsm param is the mobile phone number.
msg is the message to send.
import java.net.HttpURLConnection;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
public class Test3 {
public static void main(String[] args) throws Exception {
Test3 obj = new Test3();
System.out.println("Testing 1 - Send Http POST request");
obj.sendPost();
}
private void sendPost() throws Exception {
//
String url = "https://...url/send";//(that url its just an example, its not the real)
HttpsURLConnection httpClient = (HttpsURLConnection) new URL(url).openConnection();
//add reuqest header
httpClient.setRequestMethod("POST");
httpClient.setRequestProperty("User-Agent", "Mozilla/5.0");
httpClient.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "?user=TEST_USER&company=XXX&passwd=TEST_PWD&gsm=666000222&type=plus&msg=hello&sender=me";
// Send post request
httpClient.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(httpClient.getOutputStream())) {
wr.writeBytes(urlParameters);
wr.flush();
}
int responseCode = httpClient.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
try (BufferedReader in = new BufferedReader(
new InputStreamReader(httpClient.getInputStream()))) {
String line;
StringBuilder response = new StringBuilder();
while ((line = in.readLine()) != null) {
response.append(line);
}
System.out.println(response.toString());
}
}
}
Also If I tried to acces the the webservice call by writting the url to the navbar of Mozilla Firefox I got that error:
Secure Connection Failed
An error occurred during a connection to 'url' SSL peer was unable to negotiate an acceptable set of security parameters.
Error code: SSL_ERROR_HANDSHAKE_FAILURE_ALERT
The page you are trying to view cannot be shown because the authenticity of the received data could not be verified.
Given that the domain in question (push.tempos21.com) works for me with the browser but does not work for you neither with app nor browser, it is likely that it is not a problem of app or browser but of your connection to the target. I suspect that there is some deep inspection firewall or IPS somewhere in the path which allows the initial TCP connect but then blocks the traffic once the target is known from the ClientHello (start of TLS handshake).

How to include header information for a SOAP request in Java using HttpURLConnection

I need to introduce these header elements: Enable MTOM, Force MTOM, WSS-PasswordType: PasswordDigest, WSS TimeToLive: 50 and basic authentication with user and password, and I need to attach a document to this soap request. I have searched for documentation on HttpURLConnection but i couldn't find anything.
My code currently:
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.apache.commons.lang.StringUtils;
public class Send_XML_Post_Request_1 {
public static void main(String[] args) throws MalformedURLException, IOException {
String urlString = "https://ws1.soc.com.br/WSSoc/services/UploadArquivosWs?wsdl";
URL urlForInfWebSvc = new URL(urlString);
URLConnection UrlConnInfWebSvc = urlForInfWebSvc.openConnection();
HttpURLConnection httpUrlConnInfWebSvc = (HttpURLConnection) UrlConnInfWebSvc;
httpUrlConnInfWebSvc.setDoOutput(true);
httpUrlConnInfWebSvc.setDoInput(true);
httpUrlConnInfWebSvc.setAllowUserInteraction(true);
httpUrlConnInfWebSvc.setRequestMethod("POST");
httpUrlConnInfWebSvc.setRequestProperty("Content-Type","application/soap+xml; charset=utf-8");
OutputStreamWriter infWebSvcReqWriter = new OutputStreamWriter(httpUrlConnInfWebSvc.getOutputStream());
String infWebSvcRequestMessage = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://services.soc.age.com/\"> <soapenv:Header/> <soapenv:Body> <ser:uploadArquivo> <arg0> <arquivo></arquivo> <classificacao>FICHA_CLINICA_BRANCO</classificacao> <codigoEmpresa>297819</codigoEmpresa> <codigoFuncionario>3866</codigoFuncionario> <codigoSequencialFicha>133382762</codigoSequencialFicha> <extensaoArquivo>PDF</extensaoArquivo> <identificacaoVo> <chaveAcesso>1e93a60985ff95e</chaveAcesso> <codigoEmpresaPrincipal>62168</codigoEmpresaPrincipal> <codigoResponsavel>17863</codigoResponsavel> <homologacao>false</homologacao> <codigoUsuario>422450</codigoUsuario> </identificacaoVo> <nomeArquivo>TESTE</nomeArquivo> <sobreescreveArquivo>false</sobreescreveArquivo> </arg0> </ser:uploadArquivo> </soapenv:Body> </soapenv:Envelope>";
infWebSvcReqWriter.write(infWebSvcRequestMessage);
infWebSvcReqWriter.flush();
BufferedReader infWebSvcReplyReader = new BufferedReader(new InputStreamReader(httpUrlConnInfWebSvc.getInputStream()));
String line;
String RetornoWS = "";
while ((line = infWebSvcReplyReader.readLine()) != null) {
RetornoWS = RetornoWS.concat(line);
}
infWebSvcReqWriter.close();
infWebSvcReplyReader.close();
httpUrlConnInfWebSvc.disconnect();
String Resposta = StringUtils.substringBetween(RetornoWS,"<return>","</return>");
System.out.println(Resposta);
}
}```
You already set one header property using
httpUrlConnInfWebSvc.setRequestProperty("Content-Type","application/soap+xml; charset=utf-8");
Similar way you can pass
httpUrlConnInfWebSvc.setRequestProperty("Enable MTOM","true");
httpUrlConnInfWebSvc.setRequestProperty("Force MTOM","true");
httpUrlConnInfWebSvc.setRequestProperty("WSS-PasswordType","PasswordDigest");
httpUrlConnInfWebSvc.setRequestProperty("WSS TimeToLive","50");
For a basic authentication header, set authorization
String credentials = "user:password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(credentials.getBytes()));
httpUrlConnInfWebSvc.setRequestProperty ("Authorization", basicAuth);

How to use HTML response to extract data in Java?

So, when I am sending an HTTP request using Java language, am getting the response in the form of HTML code. For example, sending request: http://www.google.com/search?q=what%20is%20mango
getting the response in the form of HTML code of this page:
https://www.google.co.in/search?q=what+is+mango&rlz=1C1CHBF_enIN743IN743&oq=what+is+mango&aqs=chrome..69i57j0l5.4095j0j7&sourceid=chrome&ie=UTF-8
So, from this response page, I again want to send the request to Wikipedia page (listed in the response page) and then I want to copy the content about mango from the Wikipedia page and write it to a file on my system
the code from which I am sending the Google search request:
package api_test;
import java.io.*;
import java.net.*;
import java.util.*;
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();
}
private void sendGet() throws Exception{
Scanner s= new Scanner(System.in);
System.out.println("enter the URL");
String url = s.nextLine();
URL obj = new URL("http://"+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());
}
}
I think what you need is a HTML Parser, like jsoup.
You could do something like
Document doc = Jsoup.connect("http://www.google.com/search?q=what%20is%20mango").get();
Element result = doc.select("#search h3.r a").first();
String link = result.attr("data-href");
I'm not sure if Google's layout changes a lot, but right now the CSS selector "#search h3.r a" is working.

Server returned HTTP response code: 415 Unsupported media type

I have a rest web service like below.
#POST
#Path("/startProcess")
#Produces(MediaType.TEXT_PLAIN)
#Consumes(MediaType.APPLICATION_JSON)
public String startProcess(InputParams inputParams, #Context HttpServletRequest request, #Context HttpServletResponse response) {
ProjectBean projBean = new ProjectBean();
Helper.loadProjectBean(inputParams, projBean);
return "1";
}
Now I am trying to consume it with below main program.
public static void main(String[] args) throws Exception {
StringBuffer response = new StringBuffer();
String taigaServiceUrl = "http://localhost:8181/restServer/rest/TestWebService/startProcess/";
URL url = new URL(taigaServiceUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
String userpass = "admin" + ":" + "admin";
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
conn.setRequestProperty("Authorization", basicAuth);
InputParams inputParams = new InputParams();
inputParams.setXXX("xxxx");
inputParams.setYYYY("123456");
inputParams.setZZZZ("ZZZZ");
String json = new Gson().toJson(inputParams);
DataOutputStream os = new DataOutputStream (conn.getOutputStream());
os.write(json.getBytes());
os.flush();
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String inputLine;
while ((inputLine = br.readLine()) != null) {
response.append(inputLine);
}
br.close();
}
But every time I am getting below error.
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 415 for URL: http://localhost:8181/restServer/rest/TestWebService/startProcess/
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at scm.controllers.Test.main(Test.java:64)
As per error the media type is unsupported. In my rest webservice I am consuming JSON and in my main program I am sending JSON. Then where it is breaking?
Well after lot of debugging I found solution of my problem. I needed to add below jars in classpath. Actually Jersey was not able to bind JSON object to the rest service.
jackson-annotations-2.5.4.jar
jackson-core-2.5.4.jar
jackson-databind-2.5.4.jar
jackson-jaxrs-base-2.5.4.jar
jackson-jaxrs-json-provider-2.5.4.jar
jersey-entity-filtering-2.22.2.jar
jersey-media-json-jackson-2.22.2.jar
Have a look at this guide:
I think you need to define a json processor:
https://www.nabisoft.com/tutorials/java-ee/producing-and-consuming-json-or-xml-in-java-rest-services-with-jersey-and-jackson
thanks.
This is the issue with your #Produces and #Consumes.
#Produces(MediaType.TEXT_PLAIN)
#Consumes(MediaType.APPLICATION_JSON)
As per the annotation, your endpoint receives JSON and result would be TEXT.
But in your client program, you have mentioned content type as json.
conn.setRequestProperty("Content-Type", "application/json");
Hence client expects a json, where as its not.
Change this as
conn.setRequestProperty("Content-Type", "text/plain");
would work.

HTTP 403 Service Error when trying to post XML to HTTPS URL

I am trying to write a small class using the Apache HttpClient library that would do an HTTPS post to a specified URL sending some XML. When I run my code, the HTTP status line I receive back is "403 Service Error". Here's the complete error HTML returned:
$errorDump java.net.SocketTimeoutException:Read timed out
$errorInfo
$errorDump java.net.SocketTimeoutException:Read timed out
$error Read timed out
$localizedError Read timed out
$errorType java.net.SocketTimeoutException
$user
$time 2011-10-25 09:39:29 EDT
$error Read timed out
$errorType java.net.SocketTimeoutException
This is the code I am using:
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class HttpXmlPost {
public static void main(String[] args)
{
String url = "https://someurlhere.com";
String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><xmlTag></xmlTag>";
String content = request(xmlStr, url);
System.out.println(content);
}
private static String request(String xmlStr, String url) {
boolean success = false;
String content = "";
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httpPost = new HttpPost(url.trim());
InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(xmlStr.getBytes() ), -1);
reqEntity.setContentType("application/xml");
reqEntity.setChunked(true);
httpPost.setEntity(reqEntity);
System.out.println("Executing request " + httpPost.getRequestLine());
HttpResponse response = httpclient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if(response.getStatusLine().getStatusCode() == 200){
success = true;
}
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
System.out.println("Chunked?: " + resEntity.isChunked());
}
BufferedReader reader = new BufferedReader(new InputStreamReader(resEntity.getContent()));
StringBuilder buf = new StringBuilder();
char[] cbuf = new char[ 2048 ];
int num;
while ( -1 != (num=reader.read( cbuf ))) {
buf.append( cbuf, 0, num );
}
content = buf.toString();
EntityUtils.consume(resEntity);
}
catch (Exception e) {
System.out.println(e);
}
finally {
httpclient.getConnectionManager().shutdown();
}
return content;
}
}
Whatever XML I pass in doesn't seem to matter, it gives the same error no matter what. Note that this actually works with some URLs. For example, if I put https://www.facebook.com, it goes through. However, it doesn't work for my specified URL. I thought it might be a certificate issue, tried to add some code to trust any certificate, didn't seem to work either, though I may have done it wrong. Any help is appreciated.
Based on the SocketTimeoutException in the first line of the response HTML, I'm guessing that the component which implements the handler for the URL to which you are posting is having some connection problems to a source system it needs to generate the response data.
Basically, it looks like the problem is on the server, not your client.

Categories