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
Related
I've already bought a SSL certificated in my hosting, but i don't know how to implement in my java code side (using Android Studio).
This is my TLSSocketFactory.java (I copied this class from another page and I put it in my java code)
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class TLSSocketFactory extends SSLSocketFactory {
private SSLSocketFactory internalSSLSocketFactory;
public TLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, null, null);
internalSSLSocketFactory = context.getSocketFactory();
}
#Override
public String[] getDefaultCipherSuites() {
return internalSSLSocketFactory.getDefaultCipherSuites();
}
#Override
public String[] getSupportedCipherSuites() {
return internalSSLSocketFactory.getSupportedCipherSuites();
}
#Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(s, host, port, autoClose));
}
#Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port));
}
#Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port, localHost, localPort));
}
#Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port));
}
#Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(address, port, localAddress, localPort));
}
private Socket enableTLSOnSocket(Socket socket) {
if(socket != null && (socket instanceof SSLSocket)) {
((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
}
return socket;
}
}
And this is my methods to use get and post:
GET method:
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
public class JSONParser {
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
return new JSONObject(jsonText);
} finally {
is.close();
}
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
}
POST method:
public String performPostCall(String requestURL, HashMap<String, String> postDataParams) {
URL url;
StringBuffer response = new StringBuffer();
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response.append(line);
}
br.close();
}
else {
response.append("");
}
} catch (Exception e) {
e.printStackTrace();
}
return response.toString();
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
1. question N° 1: how can I mix my intance of TLSSocketFactory with my POST and GET request? Sorry for my noob question.
2. question N° 2: Have I make something in my web services? Or just getting my web services with the certificate is ok?
Thanks!
If your URL starts with https:// the returned connection is an HttpsUrlConnection on which you can set the used socket factory before connecting to the server:
TLSSocketFactory myTlsSocketFactory = new TLSSocketFactory();
...
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(myTlsSocketFactory);
You don't need a TLSSocketFactory, Android uses Apache Commons Http Client to manage that for you, see (Android - Sending HTTPS Get Request)
If you bought a certificate from a valid entity, that means the Certificate Chain is valid, to which you should not have any problems.
I recommend reading this
UPDATE I recommend using this library for HTTP Requests
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");
My application makes multiple web calls in order to get authentication. I need to store this session in a cookie. I wanted to use Cookie Manager but after doing some research, I found out it is only available to API 9 and above and my application needs to be backward compatible.
I make my web connections using HTTPURLConnection to a secure HTTPS. Quick example of my code
public String iStream_to_String(InputStream is)
{
BufferedReader rd = new BufferedReader(new InputStreamReader(is), 4096);
String line;
StringBuilder sb = new StringBuilder();
try
{
while ((line = rd.readLine()) != null)
{
sb.append(line);
}
rd.close();
} catch (IOException e)
{
e.printStackTrace();
}
String contentOfMyInputStream = sb.toString();
return contentOfMyInputStream;
}
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier()
{
public boolean verify(String hostname, SSLSession session)
{
return true;
}
};
/**
* Trust every server - dont check for any certificate
*/
private static void trustAllHosts()
{
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]
{ new X509TrustManager()
{
public java.security.cert.X509Certificate[] getAcceptedIssuers()
{
return new java.security.cert.X509Certificate[]
{};
}
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException
{
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException
{
}
} };
// Install the all-trusting trust manager
try
{
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e)
{
e.printStackTrace();
}
}
Then I make a request like so
try
{
url = new URL(url1);
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
http = https;
InputStream in = new BufferedInputStream(http.getInputStream());
sAuthenticateP1 = iStream_to_String(in);
in.close();
} catch (Exception e)
{
e.printStackTrace();
}
The full authentication is done in 4 steps. I need to have it so the session is remembered throughout the 4 steps. Seeing I can't use CookieManager, I have been looking around for other ways of doing this, but can't seem to find any. Would anyone be able to point me in the right direction.
Thanks in advance!!
Figured it out. Incase anyone else is having similar problem, will give quick outline of code. As I said before mine is a several step authentication process. So after the first request, after you have received a response, take the cookie like so
String cookie = http.getRequestProperty("Cookie");
if (cookie != null && cookie.length() > 0)
{
sCookie = cookie;
Log.v("cookie2", sCookie);
}
sCookie is a static string variable I have set up. Then in the next request, after this line
https = (HttpsURLConnection) url.openConnection();
Just put
https.setRequestProperty("Cookie", sCookie);
https.setRequestMethod("POST");
https.setDoInput(true);
https.setDoOutput(true);
And do the same thing for each request after that requires the session, and it should work fine