如何使用HTTPsURLConnection连接Android

时间:2016-01-05 08:51:09

标签: json http exception httpurlconnection

我一直试图将代码弄清楚一段时间,但是没有成功。每次应用程序崩溃时都会抛出一些随机异常。

我在youtube上的教程中学到了这段代码,尽管如此,代码对我来说并不适用。

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显示:

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

2 个答案:

答案 0 :(得分:22)

请注意,您的网址协议为 HTTP ,而非 HTTPS 。尝试使用 java.net.HttpURLConnection 对象或“https:// ...” URL。

答案 1 :(得分:0)

如果您的应用中不需要某些特定方法,例如.getResponseCode()或...,那么您也可以使用通用URLConnection类,这样就不会引入这种异常,因为它是HttpURLConnection和Https ...类的父类。不知何故。