连接 https url 时出现问题

发布于 2024-12-06 06:05:12 字数 12492 浏览 1 评论 0原文

我能够连接到 http url,但是当 服务器已移至 https,我的代码无法正常工作。 任何人都可以帮助我通过最小的改变来实现它。

我正在使用以下管理器文件(开源代码) 用于执行各种 http 请求(上传文件、 下载文件或简单的身份验证)。

我也尝试使用 httpsUrlConnection 但我想, 我在那里缺少一些东西。请建议一些东西...

public class ClientHttpRequest 
{
    HttpURLConnection connection;
    OutputStream os = null;

    public static int responseCode;
    public static String responseContentLength;

    protected void connect() throws IOException 
    {
        if (os == null) os = connection.getOutputStream();
    }

    protected void write(char c) throws IOException 
    {
        connect();
        os.write(c);
    }

    protected void write(String s) throws IOException 
    {
        connect();
        os.write(s.getBytes());
    }

    protected void newline() throws IOException 
    {
        connect();
        write("\r\n");
    }

    protected void writeln(String s) throws IOException 
    {
        connect();
        write(s);
        newline();
    }

    private static Random random = new Random();

    protected static String randomString() {
        return Long.toString(random.nextLong(), 36);
    }

    String boundary = "---------------------------" + randomString() + randomString() + randomString();

    private void boundary() throws IOException 
    {
        write("--");
        write(boundary);
    }

    /**
     * Creates a new multipart POST HTTP request on a freshly opened URLConnection
     * @param connection an already open URL connection
     * @throws IOException
     */
    public ClientHttpRequest(HttpURLConnection connection) throws IOException 
    {
        this.connection = connection;
        connection.setDoOutput(true);
        connection.setConnectTimeout(20000);
        connection.setReadTimeout(0);
        connection.setUseCaches(false);
        connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
    }

    /**
     * Creates a new multipart POST HTTP request for a specified URL
     * @param url the URL to send request to
     * @throws IOException
     */
    public ClientHttpRequest(URL url) throws IOException 
    {
        this((HttpURLConnection)url.openConnection());
    }

    /**
     * Creates a new multipart POST HTTP request for a specified URL string
     * @param urlString the string representation of the URL to send request to
     * @throws IOException
     */
    public ClientHttpRequest(String urlString) throws IOException 
    {
        this(new URL(urlString));
    }

    private void writeName(String name) throws IOException 
    {
        newline();
        write("Content-Disposition: form-data; name=\"");
        write(name);
        write('"');
    }

    /**
     * adds a string parameter to the request
     * @param name parameter name
     * @param value parameter value
     * @throws IOException
     */
    public void setParameter(String name, String value) throws IOException 
    {
        boundary();
        writeName(name);
        newline(); newline();
        writeln(value);
    }

    private static void pipe(InputStream in, OutputStream out) throws IOException 
    {
        byte[] buf = new byte[500000];
        int nread;
        int total = 0;
        synchronized (in) 
        {
            while((nread = in.read(buf, 0, buf.length)) >= 0) 
            {
                out.write(buf, 0, nread);
                total += nread;
            }
        }
        out.flush();
        buf = null;
    }

    /**
     * adds a file parameter to the request
     * @param name parameter name
     * @param filename the name of the file
     * @param is input stream to read the contents of the file from
     * @throws IOException
     */
    public void setParameter(String name, String filename, InputStream is) throws IOException 
    {
        boundary();

        writeName(name);
        write("; filename=\"");
        write(filename);
        write('"');
        newline();
        write("Content-Type: ");
        String type = URLConnection.guessContentTypeFromName(filename);
        if (type == null) 
        {
            type = "application/octet-stream";
        }
        writeln(type);
        newline();
        pipe(is, os);
        newline();
    }

    /**
     * adds a file parameter to the request
     * @param name parameter name
     * @param file the file to upload
     * @throws IOException
     */
    public void setParameter(String name, File file) throws IOException 
    {
        setParameter(name, file.getPath(), new FileInputStream(file));
    }

    /**
     * adds a parameter to the request; if the parameter is a File, the file is uploaded, otherwise the string value of the parameter is passed in the request
     * @param name parameter name
     * @param object parameter value, a File or anything else that can be stringified
     * @throws IOException
     */
    public void setParameter(String name, Object object) throws IOException 
    {
        if (object instanceof File) 
        {
            setParameter(name, (File)object);
        } 
        else 
        {
            setParameter(name, object.toString());
        }
    }

    /**
     * adds parameters to the request
     * @param parameters array of parameter names and values (parameters[2*i] is a name, parameters[2*i + 1] is a value); if a value is a file, the file is uploaded, otherwise it is stringified and sent in the request
     * @throws IOException
     */
    public void setParameters(Object[] parameters) throws IOException 
    {
        if (parameters == null) return;
        for (int i = 0; i < parameters.length - 1; i+=2) 
        {
            setParameter(parameters[i].toString(), parameters[i+1]);
        }
    }

    /**
     * posts the requests to the server, with all the cookies and parameters that were added
     * @return input stream with the server response
     * @throws IOException
     */
    public InputStream post() throws IOException 
    {
        boundary();
        writeln("--");
        os.close();

        InputStream inputStream = null;
        try
        {
            responseCode = connection.getResponseCode();
            responseContentLength = connection.getHeaderField("Content-Length");        

            inputStream = connection.getInputStream();

        }
        catch(Exception exception)
        {
            exception.printStackTrace();

            responseCode = connection.getResponseCode();

            inputStream = connection.getErrorStream();
        }

        return inputStream;
    }

    /**
     * posts the requests to the server, with all the cookies and parameters that were added before (if any), and with parameters that are passed in the argument
     * @param parameters request parameters
     * @return input stream with the server response
     * @throws IOException
     * @see setParameters
     */
    public InputStream post(Object[] parameters) throws IOException 
    {
        setParameters(parameters);
        return post();
    }

    /**
     * post the POST request to the server, with the specified parameter
     * @param name parameter name
     * @param value parameter value
     * @return input stream with the server response
     * @throws IOException
     * @see setParameter
     */
    public InputStream post(String name, Object value) throws IOException 
    {
        setParameter(name, value);
        return post();
    }

    /**
     * post the POST request to the server, with the specified parameters
     * @param name1 first parameter name
     * @param value1 first parameter value
     * @param name2 second parameter name
     * @param value2 second parameter value
     * @return input stream with the server response
     * @throws IOException
     * @see setParameter
     */
    public InputStream post(String name1, Object value1, String name2, Object value2) throws IOException 
    {
        setParameter(name1, value1);
        return post(name2, value2);
    }

    /**
     * post the POST request to the server, with the specified parameters
     * @param name1 first parameter name
     * @param value1 first parameter value
     * @param name2 second parameter name
     * @param value2 second parameter value
     * @param name3 third parameter name
     * @param value3 third parameter value
     * @return input stream with the server response
     * @throws IOException
     * @see setParameter
     */
    public InputStream post(String name1, Object value1, String name2, Object value2, String name3, Object value3) throws IOException 
    {
        setParameter(name1, value1);
        return post(name2, value2, name3, value3);
    }

    /**
     * post the POST request to the server, with the specified parameters
     * @param name1 first parameter name
     * @param value1 first parameter value
     * @param name2 second parameter name
     * @param value2 second parameter value
     * @param name3 third parameter name
     * @param value3 third parameter value
     * @param name4 fourth parameter name
     * @param value4 fourth parameter value
     * @return input stream with the server response
     * @throws IOException
     * @see setParameter
     */
    public InputStream post(String name1, Object value1, String name2, Object value2, String name3, Object value3, String name4, Object value4) throws IOException 
    {
        setParameter(name1, value1);
        return post(name2, value2, name3, value3, name4, value4);
    }

    /**
     * posts a new request to specified URL, with parameters that are passed in the argument
     * @param parameters request parameters
     * @return input stream with the server response
     * @throws IOException
     * @see setParameters
     */
    public static InputStream post(URL url, Object[] parameters) throws IOException 
    {
        return new ClientHttpRequest(url).post(parameters);
    }

    /**
     * post the POST request specified URL, with the specified parameter
     * @param name parameter name
     * @param value parameter value
     * @return input stream with the server response
     * @throws IOException
     * @see setParameter
     */
    public static InputStream post(URL url, String name1, Object value1) throws IOException 
    {
        return new ClientHttpRequest(url).post(name1, value1);
    }

    /**
     * post the POST request to specified URL, with the specified parameters
     * @param name1 first parameter name
     * @param value1 first parameter value
     * @param name2 second parameter name
     * @param value2 second parameter value
     * @return input stream with the server response
     * @throws IOException
     * @see setParameter
     */
    public static InputStream post(URL url, String name1, Object value1, String name2, Object value2) throws IOException 
    {
        return new ClientHttpRequest(url).post(name1, value1, name2, value2);
    }

    /**
     * post the POST request to specified URL, with the specified parameters
     * @param name1 first parameter name
     * @param value1 first parameter value
     * @param name2 second parameter name
     * @param value2 second parameter value
     * @param name3 third parameter name
     * @param value3 third parameter value
     * @return input stream with the server response
     * @throws IOException
     * @see setParameter
     */
    public static InputStream post(URL url, String name1, Object value1, String name2, Object value2, String name3, Object value3) throws IOException 
    {
        return new ClientHttpRequest(url).post(name1, value1, name2, value2, name3, value3);
    }

    /**
     * post the POST request to specified URL, with the specified parameters
     * @param name1 first parameter name
     * @param value1 first parameter value
     * @param name2 second parameter name
     * @param value2 second parameter value
     * @param name3 third parameter name
     * @param value3 third parameter value
     * @param name4 fourth parameter name
     * @param value4 fourth parameter value
     * @return input stream with the server response
     * @throws IOException
     * @see setParameter
     */
    public static InputStream post(URL url, String name1, Object value1, String name2, Object value2, String name3, Object value3, String name4, Object value4) throws IOException 
    {
        return new ClientHttpRequest(url).post(name1, value1, name2, value2, name3, value3, name4, value4);
    }
}

I am able to connect to http url's but when
the server moved to https, my code is not working.
Can anyone help me in geeting it right with minimal changes.

I am using the following manager file (open source code)
for doing all kind of http request (uploading file,
downloading file or simple authentications).

I tried using the httpsUrlConnection as well but i guess,
i am missing something there. Please suggest something...

public class ClientHttpRequest 
{
    HttpURLConnection connection;
    OutputStream os = null;

    public static int responseCode;
    public static String responseContentLength;

    protected void connect() throws IOException 
    {
        if (os == null) os = connection.getOutputStream();
    }

    protected void write(char c) throws IOException 
    {
        connect();
        os.write(c);
    }

    protected void write(String s) throws IOException 
    {
        connect();
        os.write(s.getBytes());
    }

    protected void newline() throws IOException 
    {
        connect();
        write("\r\n");
    }

    protected void writeln(String s) throws IOException 
    {
        connect();
        write(s);
        newline();
    }

    private static Random random = new Random();

    protected static String randomString() {
        return Long.toString(random.nextLong(), 36);
    }

    String boundary = "---------------------------" + randomString() + randomString() + randomString();

    private void boundary() throws IOException 
    {
        write("--");
        write(boundary);
    }

    /**
     * Creates a new multipart POST HTTP request on a freshly opened URLConnection
     * @param connection an already open URL connection
     * @throws IOException
     */
    public ClientHttpRequest(HttpURLConnection connection) throws IOException 
    {
        this.connection = connection;
        connection.setDoOutput(true);
        connection.setConnectTimeout(20000);
        connection.setReadTimeout(0);
        connection.setUseCaches(false);
        connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
    }

    /**
     * Creates a new multipart POST HTTP request for a specified URL
     * @param url the URL to send request to
     * @throws IOException
     */
    public ClientHttpRequest(URL url) throws IOException 
    {
        this((HttpURLConnection)url.openConnection());
    }

    /**
     * Creates a new multipart POST HTTP request for a specified URL string
     * @param urlString the string representation of the URL to send request to
     * @throws IOException
     */
    public ClientHttpRequest(String urlString) throws IOException 
    {
        this(new URL(urlString));
    }

    private void writeName(String name) throws IOException 
    {
        newline();
        write("Content-Disposition: form-data; name=\"");
        write(name);
        write('"');
    }

    /**
     * adds a string parameter to the request
     * @param name parameter name
     * @param value parameter value
     * @throws IOException
     */
    public void setParameter(String name, String value) throws IOException 
    {
        boundary();
        writeName(name);
        newline(); newline();
        writeln(value);
    }

    private static void pipe(InputStream in, OutputStream out) throws IOException 
    {
        byte[] buf = new byte[500000];
        int nread;
        int total = 0;
        synchronized (in) 
        {
            while((nread = in.read(buf, 0, buf.length)) >= 0) 
            {
                out.write(buf, 0, nread);
                total += nread;
            }
        }
        out.flush();
        buf = null;
    }

    /**
     * adds a file parameter to the request
     * @param name parameter name
     * @param filename the name of the file
     * @param is input stream to read the contents of the file from
     * @throws IOException
     */
    public void setParameter(String name, String filename, InputStream is) throws IOException 
    {
        boundary();

        writeName(name);
        write("; filename=\"");
        write(filename);
        write('"');
        newline();
        write("Content-Type: ");
        String type = URLConnection.guessContentTypeFromName(filename);
        if (type == null) 
        {
            type = "application/octet-stream";
        }
        writeln(type);
        newline();
        pipe(is, os);
        newline();
    }

    /**
     * adds a file parameter to the request
     * @param name parameter name
     * @param file the file to upload
     * @throws IOException
     */
    public void setParameter(String name, File file) throws IOException 
    {
        setParameter(name, file.getPath(), new FileInputStream(file));
    }

    /**
     * adds a parameter to the request; if the parameter is a File, the file is uploaded, otherwise the string value of the parameter is passed in the request
     * @param name parameter name
     * @param object parameter value, a File or anything else that can be stringified
     * @throws IOException
     */
    public void setParameter(String name, Object object) throws IOException 
    {
        if (object instanceof File) 
        {
            setParameter(name, (File)object);
        } 
        else 
        {
            setParameter(name, object.toString());
        }
    }

    /**
     * adds parameters to the request
     * @param parameters array of parameter names and values (parameters[2*i] is a name, parameters[2*i + 1] is a value); if a value is a file, the file is uploaded, otherwise it is stringified and sent in the request
     * @throws IOException
     */
    public void setParameters(Object[] parameters) throws IOException 
    {
        if (parameters == null) return;
        for (int i = 0; i < parameters.length - 1; i+=2) 
        {
            setParameter(parameters[i].toString(), parameters[i+1]);
        }
    }

    /**
     * posts the requests to the server, with all the cookies and parameters that were added
     * @return input stream with the server response
     * @throws IOException
     */
    public InputStream post() throws IOException 
    {
        boundary();
        writeln("--");
        os.close();

        InputStream inputStream = null;
        try
        {
            responseCode = connection.getResponseCode();
            responseContentLength = connection.getHeaderField("Content-Length");        

            inputStream = connection.getInputStream();

        }
        catch(Exception exception)
        {
            exception.printStackTrace();

            responseCode = connection.getResponseCode();

            inputStream = connection.getErrorStream();
        }

        return inputStream;
    }

    /**
     * posts the requests to the server, with all the cookies and parameters that were added before (if any), and with parameters that are passed in the argument
     * @param parameters request parameters
     * @return input stream with the server response
     * @throws IOException
     * @see setParameters
     */
    public InputStream post(Object[] parameters) throws IOException 
    {
        setParameters(parameters);
        return post();
    }

    /**
     * post the POST request to the server, with the specified parameter
     * @param name parameter name
     * @param value parameter value
     * @return input stream with the server response
     * @throws IOException
     * @see setParameter
     */
    public InputStream post(String name, Object value) throws IOException 
    {
        setParameter(name, value);
        return post();
    }

    /**
     * post the POST request to the server, with the specified parameters
     * @param name1 first parameter name
     * @param value1 first parameter value
     * @param name2 second parameter name
     * @param value2 second parameter value
     * @return input stream with the server response
     * @throws IOException
     * @see setParameter
     */
    public InputStream post(String name1, Object value1, String name2, Object value2) throws IOException 
    {
        setParameter(name1, value1);
        return post(name2, value2);
    }

    /**
     * post the POST request to the server, with the specified parameters
     * @param name1 first parameter name
     * @param value1 first parameter value
     * @param name2 second parameter name
     * @param value2 second parameter value
     * @param name3 third parameter name
     * @param value3 third parameter value
     * @return input stream with the server response
     * @throws IOException
     * @see setParameter
     */
    public InputStream post(String name1, Object value1, String name2, Object value2, String name3, Object value3) throws IOException 
    {
        setParameter(name1, value1);
        return post(name2, value2, name3, value3);
    }

    /**
     * post the POST request to the server, with the specified parameters
     * @param name1 first parameter name
     * @param value1 first parameter value
     * @param name2 second parameter name
     * @param value2 second parameter value
     * @param name3 third parameter name
     * @param value3 third parameter value
     * @param name4 fourth parameter name
     * @param value4 fourth parameter value
     * @return input stream with the server response
     * @throws IOException
     * @see setParameter
     */
    public InputStream post(String name1, Object value1, String name2, Object value2, String name3, Object value3, String name4, Object value4) throws IOException 
    {
        setParameter(name1, value1);
        return post(name2, value2, name3, value3, name4, value4);
    }

    /**
     * posts a new request to specified URL, with parameters that are passed in the argument
     * @param parameters request parameters
     * @return input stream with the server response
     * @throws IOException
     * @see setParameters
     */
    public static InputStream post(URL url, Object[] parameters) throws IOException 
    {
        return new ClientHttpRequest(url).post(parameters);
    }

    /**
     * post the POST request specified URL, with the specified parameter
     * @param name parameter name
     * @param value parameter value
     * @return input stream with the server response
     * @throws IOException
     * @see setParameter
     */
    public static InputStream post(URL url, String name1, Object value1) throws IOException 
    {
        return new ClientHttpRequest(url).post(name1, value1);
    }

    /**
     * post the POST request to specified URL, with the specified parameters
     * @param name1 first parameter name
     * @param value1 first parameter value
     * @param name2 second parameter name
     * @param value2 second parameter value
     * @return input stream with the server response
     * @throws IOException
     * @see setParameter
     */
    public static InputStream post(URL url, String name1, Object value1, String name2, Object value2) throws IOException 
    {
        return new ClientHttpRequest(url).post(name1, value1, name2, value2);
    }

    /**
     * post the POST request to specified URL, with the specified parameters
     * @param name1 first parameter name
     * @param value1 first parameter value
     * @param name2 second parameter name
     * @param value2 second parameter value
     * @param name3 third parameter name
     * @param value3 third parameter value
     * @return input stream with the server response
     * @throws IOException
     * @see setParameter
     */
    public static InputStream post(URL url, String name1, Object value1, String name2, Object value2, String name3, Object value3) throws IOException 
    {
        return new ClientHttpRequest(url).post(name1, value1, name2, value2, name3, value3);
    }

    /**
     * post the POST request to specified URL, with the specified parameters
     * @param name1 first parameter name
     * @param value1 first parameter value
     * @param name2 second parameter name
     * @param value2 second parameter value
     * @param name3 third parameter name
     * @param value3 third parameter value
     * @param name4 fourth parameter name
     * @param value4 fourth parameter value
     * @return input stream with the server response
     * @throws IOException
     * @see setParameter
     */
    public static InputStream post(URL url, String name1, Object value1, String name2, Object value2, String name3, Object value3, String name4, Object value4) throws IOException 
    {
        return new ClientHttpRequest(url).post(name1, value1, name2, value2, name3, value3, name4, value4);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

森罗 2024-12-13 06:05:12

在 HTTPS 连接中禁用证书验证的示例代码
http://exampledepot.com/egs/javax.net.ssl/TrustAll.html

sample code for Disabling Certificate Validation in an HTTPS Connection
http://exampledepot.com/egs/javax.net.ssl/TrustAll.html

风筝有风,海豚有海 2024-12-13 06:05:12

在你的java prog中使用此代码

 try {
        logger.info("Importing the Https certificate..");

        /* ----------- Importing the Https certificate -----------*/
        TrustManager[] trustAllCerts = new TrustManager[]{
            new X509TrustManager() {

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(
                        java.security.cert.X509Certificate[] certs, String authType) {
                }

                @Override
                public void checkServerTrusted(
                        java.security.cert.X509Certificate[] certs, String authType) {
                }
            }
        };
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            System.out.println("Exception" + e);
        }
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String string, SSLSession ssls) {
                return true;
            }
        });

并查看此链接你必须进行更改服务器.xml

use this code in yr java prog

 try {
        logger.info("Importing the Https certificate..");

        /* ----------- Importing the Https certificate -----------*/
        TrustManager[] trustAllCerts = new TrustManager[]{
            new X509TrustManager() {

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(
                        java.security.cert.X509Certificate[] certs, String authType) {
                }

                @Override
                public void checkServerTrusted(
                        java.security.cert.X509Certificate[] certs, String authType) {
                }
            }
        };
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            System.out.println("Exception" + e);
        }
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String string, SSLSession ssls) {
                return true;
            }
        });

and see this link u have to make change in server.xml

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文