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).
Related
I have a problem with getting XML from this webpage. In the browser it shows correctly and there is no issue, but when it comes to Java, it is different.
I've tried two methods which both of them resulted in exception.
// Method 1 - Using Java's URL
URL url = new URL(/* mentioned link */);
String rawXML = new String(url.openStream().readAllBytes(), StandardCharsets.UTF_8); // java.io.IOException: Invalid Http response
// Method 2 - Using Apache's HTTP client
HttpGet httpGet = new HttpGet(/* mentioned link */);
String rawXML = EntityUtils.toString(HttpClients.createDefault().execute(httpGet).getEntity()); // org.apache.http.ProtocolException: The server failed to respond with a valid HTTP response
Downloading this webpage with wget and using argument --content-on-error works but it is unreliable since wget is not always available on all systems like Windows.
The response does not contains headers so java rejects it
wget "https://www.strava.cz/foxisapi/foxisapi.dll/istravne.istravne.process?xmljidelnickyA&zarizeni=3148" -O so-69226464.html
--2021-09-17 13:44:29-- https://www.strava.cz/foxisapi/foxisapi.dll/istravne.istravne.process?xmljidelnickyA&zarizeni=3148
Resolving www.strava.cz (www.strava.cz)... 82.99.180.77
Connecting to www.strava.cz (www.strava.cz)|82.99.180.77|:443... connected.
HTTP request sent, awaiting response... 200 No headers, assuming HTTP/0.9
Length: unspecified
This java class making a raw HTTP GET request is able to get the contents. Based on this page.
The request sent is
GET /foxisapi/foxisapi.dll/istravne.istravne.process?xmljidelnickyA&zarizeni=3148 HTTP/1.1\r\n
User-Agent: RawHttpGet\r\n
Host: www.strava.cz\r\n
Accept: */*\r\n
Java code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import javax.net.ssl.SSLSocketFactory;
public class RawHttpGet {
private static String hostname = "www.strava.cz";
public static void main(String[] args) throws IOException {
Socket socket = SSLSocketFactory.getDefault().createSocket(hostname, 443);
// UTF-8 encdoding
//BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
// Encoding for this request
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "Cp1250"));
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuffer buff = new StringBuffer("GET /foxisapi/foxisapi.dll/istravne.istravne.process?xmljidelnickyA&zarizeni=3148 HTTP/1.1\r\n");
buff.append("User-Agent: RawHttpGet\r\n");
buff.append("Accept: */*\r\n");
buff.append("Host: " + hostname + "\r\n");
buff.append("\r\n");
System.out.println(" * Request");
System.out.println(buff.toString());
// send message
out.write(buff.toString());
out.flush();
// read response
System.out.println(" * Response");
// Default system encoding
//System.out.println(new String(socket.getInputStream().readAllBytes()));
// Encoding for this request
System.out.println(new String(socket.getInputStream().readAllBytes(), "Cp1250"));
out.close();
in.close();
}
}
I need to invoke a REST call from Java code.
I have credentials in the form of
Id
Security Key
An algorithm provided which
Gets the server time
Using Id, security key & server time it generates a security token
Now authorization is in the below form
"Authorization": "name id=Id, serverTime=serverTime, securitytoken=securitytoken"
Need a java client program to invoke this REST call using above authorization header.
I am getting
HTTP Response 401 error.
Please provide correct way to set authorization header in request for form
Name Id="Id",serverTime="2017-11-18T05:51:05",securityToken="TOKEN"
Code:
package com.rest.client;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Sample {
public final static String GATEWAY_ID = "Id";
public final static String KEY = "Key";
public static void main(String[] args) {
try {
HttpURLConnection conn;
conn = (HttpURLConnection) new URL("https://domain/A/B/72968").openConnection();
String serverTime = "2017-11-18T10:51:05";
String securityToken = "TOKEN";
String authorization = "Name Id=\"" + GATEWAY_ID + "\",serverTime=\"" + serverTime + "\",securityToken=\""
+ securityToken + "\"";
// Name Id="Id",serverTime="2017-11-18T10:51:05",securityToken="TOKEN"
conn.addRequestProperty("Authorization", authorization); // Is Header set is correct? It should be part of Request Header. Please correct this
int status = conn.getResponseCode();
System.out.println(status);
BufferedReader br = null;
StringBuilder body = null;
String line = "";
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
body = new StringBuilder();
while ((line = br.readLine()) != null) {
body.append(line);
}
System.out.println(body);
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
Error:
java.io.IOException: Server returned HTTP response code: 401 for URL: https://domain/A/B/72968
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1926)
at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1921)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1920)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1490)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at com.rest.client.ApplicationClient.main(ApplicationClient.java:48)
Caused by: java.io.IOException: Server returned HTTP response code: 401 for URL: https://domain/A/B/72968
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1876)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338)
at com.rest.client.ApplicationClient.main(ApplicationClient.java:38)
try format authorization string this way "Basic Base64". try
authorization ="Basic "+new String(new Base64().encode(authorization.getBytes()));
conn.setRequestProperty("Authorization", authorization);
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?
I am trying to make a http get request using java ,when i am executing the code ,i am getting 403 forbiddencode .Is there any way to get rid of that ?my code is
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;
public class Http {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String [] args){
Http http=new Http();
try {
http.get();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void get() throws Exception{
URL ob=new URL("http://www.google.com/search?q=vamsi");
HttpURLConnection con=(HttpURLConnection) ob.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("USER_AGENT", USER_AGENT);
int responseCode=con.getResponseCode();
System.out.println("Response code is "+responseCode);
BufferedReader buf=new BufferedReader(new InputStreamReader(con.getInputStream()));
String input;
StringBuffer response =new StringBuffer();
while((input=buf.readLine())!=null){
response.append(input);
}
buf.close();
System.out.println(response.toString());
}
}
Google Search will deny your request if you are doing it outside of their API and Terms of Service.
$ wget http://www.google.com/search?q=vamsi
Resolving www.google.com (www.google.com)... 74.125.225.212, 74.125.225.210, 74.125.225.211, ...
Connecting to www.google.com (www.google.com)|74.125.225.212|:80... connected.
HTTP request sent, awaiting response... 403 Forbidden
2014-02-01 23:21:08 ERROR 403: Forbidden.
They may be looking at your User-Agent header. If you add one that resembles a browser, it may work, though you are circumventing the Terms of Service and seeking unsupported behavior. (Sorry, I too tried this once.)
See also Why does Google Search return HTTP Error 403?
FYI, this is a common restriction of major search engines (Google, Bing, Yahoo). There are some that you can query programatically; you will have to use those.
This is the solution:
con.setRequestProperty("User-Agent", USER_AGENT);
I'm trying to establish a Connection via HTTPS. I also set the "Authorization" property in the Request Header to Basic and provide an encoded auth string accordingly.
I checked with the Firefox Plugin HttpRequester and everythign works fine, which means I entered the url, choose "GET" as request method, add the Authorization to the header and after pressing submit I get back some xml which only a properly authorized user should get.
Unfortunately I can neither provide you with the actual auth info nor the real url in the SSCCE. However, I can tell you, that the Auth seems to work, since I get a 200 response. I also changed the Auth to a wrong value and get a "401 Authorization Required" response then.
It actually seems like the "?myparam=xyz" is somehow cut off, because when I remove this parameter from the url and test with Firefox HttpRequester again I get the same response as in Java.
Unfortunately I have no access to "theirdomain.com", so I don't know what's happending on the server side. But since it works with the Firefox HttpRequester, it should also work with Java.
What could be the reason? Thanks for your help!
EDIT:
I changed the url to "https://www.google.com/search?q=foo" and commented this line:
//con.setRequestProperty("Authorization", auth);
I can see from the returned string, that google received the "foo". So apparently the combination of Authorization and get parameter seems to be the problem, since both separately work fine.
SSCCE:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class HttpRequest
{
/**
* #param args
*/
public static void main(final String[] args)
{
System.out.println("start request");
final String urlString = "https://theirdomain.com/foo/bar/bob?myparam=xyz";
final String auth = "Basic XyzxYzxYZxYzxyzXYzxY==";
HttpsURLConnection con;
try
{
final URL url = new URL(urlString);
con = (HttpsURLConnection) url.openConnection();
con.setRequestProperty("Authorization", auth);
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
con.setRequestMethod("GET");
// con.setDoOutput(true);
con.connect();
final int responseCode = con.getResponseCode();
if (responseCode != 200)
System.out.println("Server responded with code " + responseCode + " " + con.getResponseMessage());
else
{
System.out.println("Starting to read...");
final InputStream inStream = con.getInputStream();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c;
while (inStream != null && (c = inStream.read()) != -1)
{
baos.write(c);
}
System.out.println(new String(baos.toByteArray()));
}
}
catch (final IOException e)
{
System.out.println("could not open an HTTP connection to url: " + urlString);
e.printStackTrace();
}
finally
{
System.out.println("end request");
}
}
}
Have you tried adding
con.setRequestProperty("myparam", "xyz"); to your code?