Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect Android with HTTPsURLConnection

I've been trying to figure the code out for quite a while now, however have had no success. Everytime the App crashes by throwing some random exception.

I learnt this code off a tutorial on youtube and despite that, the code doesn't work for me.

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.Buffer;

import javax.net.ssl.HttpsURLConnection;

public class MainActivity extends AppCompatActivity {
Button b1;
TextView t1;
private Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b1=(Button)findViewById(R.id.bthhit);
    t1=(TextView)findViewById(R.id.tvJSONitem);

    b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt");
        }
    });

}

public class JSONTask extends AsyncTask<String,String,String>{
    HttpsURLConnection connection = null;
    BufferedReader reader = null;

    @Override
    protected String doInBackground(String... params) {

        try {
            URL url=new URL(params[0]);
            connection= (HttpsURLConnection)url.openConnection();
            connection.connect();

            InputStream stream= connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));
            String line;
            StringBuffer buffer= new StringBuffer();
            while((line=reader.readLine())!=null){
                buffer.append(line);
            }

            return buffer.toString();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(connection!=null) {
                connection.disconnect();
            }
            try {
                if(reader!=null){
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        t1.setText(result);

    }
}
}

Logcat shows this:

01-05 00:46:09.018 5573-5580/? E/art: Failed sending reply to debugger: Broken pipe
01-05 00:46:17.852 5573-5706/com.example.test.jsonparser E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
   Process: com.example.test.jsonparser, PID: 5573
   java.lang.RuntimeException: An error occurred while executing doInBackground()
       at android.os.AsyncTask$3.done(AsyncTask.java:309)
       at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
       at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
       at java.util.concurrent.FutureTask.run(FutureTask.java:242)
       at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
       at java.lang.Thread.run(Thread.java:818)
    Caused by: java.lang.ClassCastException: com.android.okhttp.internal.huc.HttpURLConnectionImpl cannot be cast to javax.net.ssl.HttpsURLConnection
       at com.example.test.jsonparser.MainActivity$JSONTask.doInBackground(MainActivity.java:58)
       at com.example.test.jsonparser.MainActivity$JSONTask.doInBackground(MainActivity.java:49)
       at android.os.AsyncTask$2.call(AsyncTask.java:295)
       at java.util.concurrent.FutureTask.run(FutureTask.java:237)
       at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
       at java.lang.Thread.run(Thread.java:818) 
01-05 00:46:19.104 5573-5587/com.example.test.jsonparser E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab792110
like image 221
Addy Avatar asked Jan 05 '16 08:01

Addy


People also ask

What is HTTP URL connection in Android?

HttpURLConnection uses the GET method by default. It will use POST if setDoOutput(true) has been called. Other HTTP methods ( OPTIONS , HEAD , PUT , DELETE and TRACE ) can be used with setRequestMethod(String) .

What is the difference between HttpURLConnection and HttpsURLConnection?

URLConnection is the base class. HttpURLConnection is a derived class which you can use when you need the extra API and you are dealing with HTTP or HTTPS only. HttpsURLConnection is a 'more derived' class which you can use when you need the 'more extra' API and you are dealing with HTTPS only.

How do I close URLConnection on Android?

Once the response body has been read, the HttpURLConnection should be closed by calling disconnect() .


1 Answers

Please note that your URL protocol is HTTP and not HTTPS. Try either using a java.net.HttpURLConnection object or a "https://..." URL.

like image 111
J-Cint Avatar answered Oct 12 '22 01:10

J-Cint