I want to download a response of the below wget command in windows:
wget --no-check-certificate --post-data 'login=xxx&password=yyy' https://AAA.BBB.CCC.DDD:1234/login -O -
This command works fine in linux, but it's not working in windows. I know if I install wget on windows, then it will work. I want to run it without installing it. I want the option for above wget command for above specified url to achieve the target.
So far i have tried the below snippet of code But it only returns html info (source code) of the page without going to the homepage using username and password.
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.codec.binary.Base64;
public class ConnectToUrlUsingBasicAuthentication
{
static
{
disableSslVerification();
}
private static void disableSslVerification()
{
try
{
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier()
{
public boolean verify(String hostname, SSLSession session)
{
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (KeyManagementException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
try
{
String webPage = "https://AAA.BBB.CCC.DDD:1234/login";
String name = "xxx";
String password = "yyy";
String authString = name + ":" + password;
System.out.println("auth string: " + authString);
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
System.out.println("Base64 encoded auth string: " + authStringEnc);
URL url = new URL(webPage);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
javax.net.ssl.HostnameVerifier myHv = new javax.net.ssl.HostnameVerifier(){
public boolean verify(String
hostName,javax.net.ssl.SSLSession session) { return true; }
};
((HttpsURLConnection) urlConnection).setHostnameVerifier(myHv); urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0)
{
sb.append(charArray, 0, numCharsRead);
}
String result = sb.toString();
System.out.println("*** BEGIN ***");
System.out.println(result);
System.out.println("*** END ***");
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Related
We're trying to make secure http communication between client an server.
The server provided the certificates, we took them, install them and we start running, the point is to exchange an exact number of messages simultaneously between the client and server consecutively, the problem that's driving us crazy is that between the requests, at SSLHANDSHAKE we get randomly the exception javax.net.ssl.SSLException: Received fatal alert: unexpected_message exactly at ServerHello handshake phase, and i don't know how or why this is happening while it keeps working fine for 98% of the other requests.
it crashes at step 2.
Transporter.java : This is the class responsible for sending and receiving the data.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.KeyStore;
import java.util.ResourceBundle;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
public class Transporter {
private static ResourceBundle resource = ResourceBundle.getBundle("resourece_00");
private static final String keystore = resource.getString("server_keystore");
private static final String truststore = resource.getString("server_truststore");
private static final String keypass = resource.getString("server_keystore_pwd");
private static final String trustpass = resource.getString("server_truststore_pwd");
// secure channel variables
private static SSLSocketFactory sslSocketFactory = null;
public Transporter() {
// setupSocketFactory();
}
static {
try {
String protocol = "TLS";
String type = "JKS";
String algorithm = KeyManagerFactory.getDefaultAlgorithm();
String trustAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
// create and initialize an SSLContext object
SSLContext sslContext = SSLContext.getInstance(protocol);
sslContext.init(getKeyManagers(type, algorithm), getTrustManagers(type, trustAlgorithm), null);
// obtain the SSLSocketFactory from the SSLContext
sslSocketFactory = sslContext.getSocketFactory();
} catch (Exception e) {
e.printStackTrace();
}
}
private static KeyStore getStore(String type, String filename, String pwd) throws Exception {
KeyStore ks = KeyStore.getInstance(type);
InputStream istream = null;
try {
File ksfile = new File(filename);
istream = new FileInputStream(ksfile);
ks.load(istream, pwd != null ? pwd.toCharArray() : null);
} finally {
if (istream != null) {
istream.close();
}
}
return ks;
}
private static KeyManager[] getKeyManagers(String type, String algorithm) throws Exception {
KeyStore ks = getStore(type, keystore, keypass);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
kmf.init(ks, keypass.toCharArray());
return kmf.getKeyManagers();
}
private static TrustManager[] getTrustManagers(String type, String algorithm) throws Exception {
KeyStore ts = getStore(type, truststore, trustpass);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
tmf.init(ts);
return tmf.getTrustManagers();
}
public String sendToVD(String msg, String urll, Long timeOut) {
byte[] bytes = msg.getBytes();
HttpsURLConnection sconn = null;
URL url = null;
OutputStream out = null;
BufferedReader read = null;
String recu = null;
try {
url = new URL(urll);
sconn = (HttpsURLConnection) url.openConnection();
sconn.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession sslSession) {
return true;
}
});
sconn.setSSLSocketFactory(sslSocketFactory);
// sconn.setReadTimeout((timeOut.intValue()) * 1000);// set timeout
sconn.setRequestMethod("POST");
sconn.addRequestProperty("Content-Length", "" + bytes.length);
sconn.setRequestProperty("Content-Type", "application/xml; charset=utf-8");
sconn.setDoOutput(true);
sconn.setDoInput(true);
// send POST data
// This is the crash location
out = sconn.getOutputStream();
// OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
out.write(bytes);
out.flush();
// logger.info("flush!!!!!!!!!!!!!");
// out.close();
read = new BufferedReader(new InputStreamReader(sconn.getInputStream()));
String query = null;
recu = read.readLine();
while ((query = read.readLine()) != null) {
recu += query;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// close all connections here
if (out != null)
out.close();
if (read != null)
read.close();
if (sconn != null)
sconn.disconnect();
} catch (Exception ce) {
}
}
return recu;
}
}
The function sendToVD() does the main work of the exchange between the client and the server.
At Client-End :
A web application with JSF managing the front layer, spring managing the beans life cycle, the communication entry to the client is assured by Servlets.
The client is deployed in a RedHat Linux machine, all TLS_VERSIONS are enbaled, JDK_8.
At Server-Side: i can't post the detailed information about the target URL for security measures, but it follows the following pattern https://ip:port/path, and it supports TLS_v1.2.
Hope you can help me out.
While I was changing from open weather api to dark sky api, I found a problem with the connection.
I simply want to get the JSON-response from that api and with the open weather map api, everything worked just well. Now I decided to use the dark sky api instead. I just adapted everything as always but it doesn't work.
Maybe it has a problem with https? (the dark sky api uses an https-URL where the open weather map api used an http-URL).
Anyway, I catch an IOException in
inputStream = connection.getInputStream();
Here is my class:
import com.nymvno.hiob.prototyp_v30.Utils.Utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class WeatherHttpClient {
public String getWeatherData(String place) {
HttpURLConnection connection;
InputStream inputStream;
try {
connection = (HttpURLConnection) (new URL(Utils.BASE_URL + place)).openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
//Read the response
StringBuffer stringBuffer = new StringBuffer();
inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line + "\r\n");
}
inputStream.close();
connection.disconnect();
return stringBuffer.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
You must have to varify your host name from your Application class
check my code
public class MyApp extends Application{
#Override
public void onCreate(){
super.onCreate();
handleSSLHandshake();
}
#SuppressLint("TrulyRandom")
public static void handleSSLHandshake() {
try {
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
#Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
#Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
#Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
}};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession arg1) {
if(hostname.equalsIgnoreCase("your host name")){
return true;
}else {
return false;
}
}
});
} catch (Exception ignored) {
}
}
}
As you have mentioned, there is just a difference of http/https protocol. For URLS, having https protocols, you must use HttpsURLConnection API rather than HttpURLConnection. If you use HttpURLConnection API for https url exception will be thrown. For further details you may refer below link.
https://developer.android.com/reference/javax/net/ssl/HttpsURLConnection.html
I am beginner to android.
I am working on client side code I have to read images store on server and display it in imageview.
I have refer some stackoverflow question but not able to succeed.
I did simple plain java program with HttpsURLConnection class I got the some binary response from server for image, thats ok with plain java code.
But when I tried the same thing in android with little bit change in code, I got the Exception:
01-29 18:39:28.199: WARN/System.err(2045): java.io.IOException: SSL handshake failure: I/O error during system call, Unknown error: 0
01-29 18:39:28.249: WARN/System.err(2045): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.nativeconnect(Native Method)
01-29 18:39:28.249: WARN/System.err(2045): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:316)
01-29 18:39:28.249: WARN/System.err(2045): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.getSecureSocket(HttpConnection.java:168)
01-29 18:39:28.249: WARN/System.err(2045): at org.apache.harmony.luni.internal.net.www.protocol.https.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:399)
This is my public URL of sample image:
https://s3-ap-southeast-1.amazonaws.com/edt-demo-app/app-images/Mobile.jpg
The code which works fine for me in plain java is as follows:
package com.psl.dao;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
mport javax.net.ssl.HttpsURLConnection;
public class HttpsClient{
public static void main(String[] args)
{
String url = "https://s3-ap-southeast-1.amazonaws.com/edt-demo-app/app-images/Mobile.jpg";
try {
new HttpsClient().print(url);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void print(String url)throws Exception
{
String httpsURL = url;
URL myurl = new URL(httpsURL);
System.setProperty("https.proxyHost", "puproxy.company.co.in");
System.setProperty("https.proxyPort", "8080");
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
System.out.println(con.toString());
InputStream ins = con.getInputStream();
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader in = new BufferedReader(isr);
String inputLine;
while ((inputLine = in.readLine()) != null)
{
System.out.println(inputLine);
}
in.close();
}
}
Then I have refer some android tutorial and tried following code in my android app:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class TestSSL {
public static void main(String[] args) throws Exception {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
// Install the all-trusting trust manager
final SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
System.setProperty("https.proxyHost", "puproxy.company.co.in");
System.setProperty("https.proxyPort", "8080");
URL url = new URL("https://s3-ap-southeast-1.amazonaws.com/edt-demo-app/app-images/Mobile.jpg");
URLConnection con = url.openConnection();
final Reader reader = new InputStreamReader(con.getInputStream());
final BufferedReader br = new BufferedReader(reader);
String line = "";
while ((line = br.readLine()) != null) {
Log.d("tag",line+"");
}
br.close();
} // End of main
} // End of the class //
But I got exception as above said:
01-29 18:39:28.199: WARN/System.err(2045): java.io.IOException: SSL handshake failure: I/O error during system call, Unknown error: 0
Any other code that works fine with Apache HttpClient or Async HttP client library by using Asynynchronusly loading of image would welcome.
Also I dont know how to do proxy setting in android. so please do it for me with respective parameter
I have tried follwing tutorial but my image is not displayed.
http://javatechig.com/android/download-image-using-asynctask-in-android
The above tutorial works fine for Http URL but not for Https
I want code like in above tutorial that works fine for HTTPS URL For time being consider server certificate is not important for me.
Please try this code
MainActivity
package com.example.androidhttpsdemo;
/*
*
* MainActivity.java
* #author Santosh Shinde
* Date: 30/01/2015 12:28:16 PM
*
*/
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.net.ssl.HttpsURLConnection;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends Activity {
//public static final String URL ="https://googledrive.com/host/0B_DiX4MiMa3HTHdiYVRmUHBMcW8/image1.jpg";
public static final String URL="https://s3-ap-southeast-1.amazonaws.com/edt-demo-app/app-images/Mobile.jpg";
ImageView imageView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.ImageView1);
// Create an object for subclass of AsyncTask
GetXMLTask task = new GetXMLTask();
// Execute the task
task.execute(new String[] { URL });
}
private class GetXMLTask extends AsyncTask {
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
// Sets the Bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
System.out.println("finished");
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.
decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpsURLConnection httpConnection = (HttpsURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpsURLConnection.HTTP_OK ||
httpConnection.getResponseCode() == HttpsURLConnection.HTTP_NOT_MODIFIED ) {
stream = httpConnection.getInputStream();
} else { // just in case..
//log.d("Surprize HTTP status was: " ,httpConnection.getResponseCode());
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
}
try this code...
try
{
InputStream imageURL = new URL (url).openStream();
bitmap = BitmapFactory.decodeStream(imageURL);
}
catch (Exception e)
{
e.printStackTrace();
}
Best solution is
Android-Universal-Image-Loader, it is very simple to use.
You can simply set dataBinding in your build.gradle to true add Glide Lib to load Images nicely
android {
compileSdkVersion 25
buildToolsVersion '25.0.3'
dataBinding {
enabled = true
}
...
}
And create a BindingAdapter, this will overwrite the current method(in this case
android:src="...") and load the image.
#BindingAdapter("android:src")
public static void setImageUrl(ImageView imageView, String url) {
Context context = imageView.getContext();
Glide.with(context).load(url).into(imageView);
}
Now you can just simple pass an url in the xml and it will load the Image, this method can be placed anywhere in the code.
<ImageView
android:id="#+id/status_avatar"
android:layout_width="64dp"
android:layout_height="64dp"
android:src="http://knightwise.com/wp-content/uploads/2014/02/android-apple-wallpaper.jpg"/>
I am trying to download the web content from Google https as in the link below.
link to download
With the code below, I first disable the validation of certificates for testing purposes and trust all certificates, and then download the web as regular http, but for some reason, it is not successful:
public static void downloadWeb() {
// Create a new trust manager that trust all certificates
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
} };
// Activate the new trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {}
//begin download as regular http
try {
String wordAddress = "https://www.google.com/webhp?hl=en&tab=ww#hl=en&tbs=dfn:1&sa=X&ei=obxCUKm7Ic3GqAGvoYGIBQ&ved=0CDAQBSgA&q=pronunciation&spell=1&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.&fp=c5bfe0fbd78a3271&biw=1024&bih=759";
URLConnection yc = new URL(wordAddress).openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine = "";
while ((inputLine = in.readLine()) != null) {
System.out.println(wordAddress);
}
} catch (IOException e) {}
}
You need to fake HTTP headers so that google think that you are downloading it from a web browser. Here is a sample code using HttpClient:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class App1 {
public static void main(String[] args) throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://_google_url_");
httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:8.0) Gecko/20100101 Firefox/8.0");
HttpResponse execute = httpclient.execute(httpget);
File file = new File("google.html");
FileOutputStream fout = null;
try {
fout = new FileOutputStream(file);
execute.getEntity().writeTo(fout);
} finally {
if (fout != null) {
fout.close();
}
}
}
}
Warning, I am not responsible if you use this code and violate Google's term of service agreement.
Iam unable to post the data to the server, getting error as . But it is working fine in curl script.
Error reading URL
java.io.IOException: Server returned HTTP response code: 415 for URL: https://8.7.177.4/api/domains/amj.nms.mixnetworks.net/subscribers/9001?do_not_disturb=no
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at CurlAuthentication.authenticatePostUrl(CurlAuthentication.java:109)
at CurlAuthentication.main(CurlAuthentication.java:134)
Error reading URL
Below is the code.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
public class CurlAuthentication {
public void authenticatePostUrl() {
HostnameVerifier hv = new HostnameVerifier() {
#Override
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: " + urlHostName
+ " vs. " + session.getPeerHost());
return true;
}
};
// Now you are telling the JRE to trust any https server.
// If you know the URL that you are connecting to then this should
// not be a problem
try {
trustAllHttpsCertificates();
} catch (Exception e) {
System.out.println("Trustall" + e.getStackTrace());
}
HttpsURLConnection.setDefaultHostnameVerifier(hv);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
try {
URL url = new URL("www.stackoverflow.com");
String credentials = "user" + ":" + "password";
String encoding = Base64Converter.encode(credentials.getBytes("UTF-8"));
HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
uc.setDoInput(true);
uc.setDoOutput(true);
uc.setRequestProperty("Authorization", String.format("Basic %s", encoding));
uc.setRequestMethod("POST");
uc.setRequestProperty("Content-Type", "application/xml");
uc.setRequestProperty("Accept", "application/xml");
uc.getInputStream();
System.out.println(uc.getContentType());
InputStream content = (InputStream) uc.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(
content));
String line;
while ((line = in.readLine()) != null) {
pw.println(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
pw.println("Invalid URL");
} catch (IOException e) {
e.printStackTrace();
pw.println("Error reading URL");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(sw.toString());
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CurlAuthentication au = new CurlAuthentication();
au.authenticatePostUrl();
}
// Just add these two functions in your program
public static class TempTrustedManager implements
javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
}
private static void trustAllHttpsCertificates() throws Exception {
// Create a trust manager that does not validate certificate chains:
javax.net.ssl.TrustManager[] trustAllCerts =
new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new TempTrustedManager();
trustAllCerts[0] = tm;
javax.net.ssl.SSLContext sc =
javax.net.ssl.SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(
sc.getSocketFactory());
}
}
Do iam doing anything wrong from the above code?
DO i need to use curl script to post the data?
Well, as Error 415 is already stating:
415 Unsupported Media Type
The request entity has a media type which the server or resource does not support. For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.
Without knowing the specifications of what the server is expecting of you to send him, it's hard to tell what you are missing. It though seems as if you only want to receive data from the server and not send him anything.
By setting uc.setRequestProperty("Content-Type", "application/xml"); you tell the server that you hand him over some XML data (which you don't) and he probably also wouldn't expect this, so he's giving you that error.
As your sending some urlencoded data in your POST data, try setting this to:
uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");