0

我正在尝试制作一个从在线服务器获取信息的 android 应用程序,并且我正在使用 httpurlconnection 但我不断收到 SSL 异常

我已经在线检查了解决方案,但我无法让它工作

这是完整的堆栈跟踪:

javax.net.ssl.SSLException: Connection closed by peer
        at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
        at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:405)
        at com.android.okhttp.Connection.upgradeToTls(Connection.java:146)
        at com.android.okhttp.Connection.connect(Connection.java:107)
        at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:294)
        at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
        at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
        at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
        at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
        at com.android.okhttp.internal.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:161)
        at com.tritech.agric.tritechagric.ProjectUtils.makeHttpRequest(ProjectUtils.java:91)
        at com.tritech.agric.tritechagric.ProjectUtils.fetchProjectData(ProjectUtils.java:35)
        at com.tritech.agric.tritechagric.ProjectLoader.loadInBackground(ProjectLoader.java:31)
        at com.tritech.agric.tritechagric.ProjectLoader.loadInBackground(ProjectLoader.java:10)
        at android.support.v4.content.AsyncTaskLoader.onLoadInBackground(AsyncTaskLoader.java:307)
        at android.support.v4.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:60)
        at android.support.v4.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:48)
        at android.support.v4.content.ModernAsyncTask$2.call(ModernAsyncTask.java:141)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:841)

这是我的代码:

package com.tritech.agric.tritechagric;

import android.text.TextUtils;
import android.util.Log;

import org.json.JSqONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReeader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class ProjectUtils {

    /** Tag for the log messages */
    private static final String LOG_TAG = ProjectUtils.class.getSimpleName();

    /**
     * Query the Tritech Agric dataset and return a {@link Project} object to represent a single project.
     */
    public static List<Project> fetchProjectData(String requestUrl) {
        URL url = createUrl(requestUrl);
        List<Project> projects = null;

        try {
            String jsonResponse = makeHttpRequest(url);
            projects = extractFeatureFromJson(jsonResponse);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return projects;
    }

    /**
     * Returns new URL object from the given string URL.
     */
    private static URL createUrl(String stringUrl) {
        URL url = null;

        if(stringUrl == null) {
            return url;
        }

        try {
            url = new URL(stringUrl);
        } catch (MalformedURLException e) {
            Log.e(LOG_TAG, "Error with creating URL ", e);
        }
        return url;
    }

    /**
     * Make an HTTP request to the given URL and return a String as the response.
     */
    private static String makeHttpRequest(URL url) throws IOException {
        String jsonResponse = "";

        // If the URL is null, then return early.
        if (url == null) {
            return jsonResponse;
        }

        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        String consumerKey = "ck_f66d9606a38af1579931d1fb66eb453451aa4ea6";
        String consumerSecret = "cs_37d789450fb2d4f09eaeb08ddb951c281478e43f";
        String consumerKeyAndSecret = consumerKey + ":" + consumerSecret;
        byte[] encodeValue = android.util.Base64.encode(consumerKeyAndSecret.getBytes(), android.util.Base64.DEFAULT);
        String value = new String(encodeValue);
        String basicAuthPayload = ("Basic " + value);
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
//            urlConnection.setReadTimeout(10000 /* milliseconds */);
//            urlConnection.setConnectTimeout(15000 /* milliseconds */);
            urlConnection.setRequestMethod("GET");

            // Include the HTTP Basic Authentication payload
            urlConnection.addRequestProperty("Authorization", basicAuthPayload);

            urlConnection.connect();

            // If the request was successful (response code 200),
            // then read the input stream and parse the response.
            if (urlConnection.getResponseCode() == 200) {
                inputStream = urlConnection.getInputStream();
                jsonResponse = readFromStream(inputStream);
            } else {
                Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "Problem retrieving the project JSON results.", e);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return jsonResponse;
    }

    /**
     * Convert the {@link InputStream} into a String which contains the
     * whole JSON response from the server.
     */
    private static String readFromStream(InputStream inputStream) throws IOException {
        StringBuilder output = new StringBuilder();
        if (inputStream != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = reader.readLine();
            while (line != null) {
                output.append(line);
                line = reader.readLine();
            }
        }
        return output.toString();
    }

    /**
     * Return a {@link Project} object by parsing out information
     * about the first project from the input projectJSON string.
     */
    private static ArrayList<Project> extractFeatureFromJson(String projectJSON) {
        // If the JSON string is empty or null, then return early.
        if (TextUtils.isEmpty(projectJSON)) {
            return null;
        }

        ArrayList<Project> projects = new ArrayList<>();

        try {
            JSONArray baseJsonResponse = new JSONArray(projectJSON);
            if (baseJsonResponse.length() > 0) {
                for (int i = 0; i < baseJsonResponse.length(); i++) {
                    JSONObject projectObject = baseJsonResponse.getJSONObject(i);
                    JSONObject title = projectObject.getJSONObject("title");



                    // Extract out the title, number of people, and perceived strength values
                    String projectName = title.getString("rendered");
                    String projectPrice = "NGN " + projectObject.getString("price");
                    String projectLocation = projectObject.getString("project_location");
                    String roi = projectObject.getString("project_roi");


                    // Create a new {@link Project} object
                    Project project = new Project(projectName, projectPrice, projectLocation, roi);
                    projects.add(project);

                }

                return projects;

            }
        } catch (JSONException e) {
            Log.e(LOG_TAG, "Problem parsing the earthquake JSON results", e);
        }
        return projects;
    }

}

如果我能得到一些帮助,我将不胜感激

4

0 回答 0