Java调用https接口添加证书

  • 使用InstallCert.Java生成证书

/*
 * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
 
import java.io.*;
import java.net.URL;
 
import java.security.*;
import java.security.cert.*;
 
import javax.net.ssl.*;
 
public class InstallCert {
 
    public static void main(String[] args) throws Exception {
	String host;
	int port;
	char[] passphrase;
	if ((args.length == 1) || (args.length == 2)) {
	    String[] c = args[0].split(":");
	    host = c[0];
	    port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
	    String p = (args.length == 1) ? "changeit" : args[1];
	    passphrase = p.toCharArray();
	} else {
	    System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
	    return;
	}
 
	File file = new File("jssecacerts");
	if (file.isFile() == false) {
	    char SEP = File.separatorChar;
	    File dir = new File(System.getProperty("java.home") + SEP
		    + "lib" + SEP + "security");
	    file = new File(dir, "jssecacerts");
	    if (file.isFile() == false) {
		file = new File(dir, "cacerts");
	    }
	}
	System.out.println("Loading KeyStore " + file + "...");
	InputStream in = new FileInputStream(file);
	KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
	ks.load(in, passphrase);
	in.close();
 
	SSLContext context = SSLContext.getInstance("TLS");
	TrustManagerFactory tmf =
	    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	tmf.init(ks);
	X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
	SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
	context.init(null, new TrustManager[] {tm}, null);
	SSLSocketFactory factory = context.getSocketFactory();
 
	System.out.println("Opening connection to " + host + ":" + port + "...");
	SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
	socket.setSoTimeout(10000);
	try {
	    System.out.println("Starting SSL handshake...");
	    socket.startHandshake();
	    socket.close();
	    System.out.println();
	    System.out.println("No errors, certificate is already trusted");
	} catch (SSLException e) {
	    System.out.println();
	    e.printStackTrace(System.out);
	}
 
	X509Certificate[] chain = tm.chain;
	if (chain == null) {
	    System.out.println("Could not obtain server certificate chain");
	    return;
	}
 
	BufferedReader reader =
		new BufferedReader(new InputStreamReader(System.in));
 
	System.out.println();
	System.out.println("Server sent " + chain.length + " certificate(s):");
	System.out.println();
	MessageDigest sha1 = MessageDigest.getInstance("SHA1");
	MessageDigest md5 = MessageDigest.getInstance("MD5");
	for (int i = 0; i < chain.length; i++) {
	    X509Certificate cert = chain[i];
	    System.out.println
	    	(" " + (i + 1) + " Subject " + cert.getSubjectDN());
	    System.out.println("   Issuer  " + cert.getIssuerDN());
	    sha1.update(cert.getEncoded());
	    System.out.println("   sha1    " + toHexString(sha1.digest()));
	    md5.update(cert.getEncoded());
	    System.out.println("   md5     " + toHexString(md5.digest()));
	    System.out.println();
	}
 
	System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
	String line = reader.readLine().trim();
	int k;
	try {
	    k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
	} catch (NumberFormatException e) {
	    System.out.println("KeyStore not changed");
	    return;
	}
 
	X509Certificate cert = chain[k];
	String alias = host + "-" + (k + 1);
	ks.setCertificateEntry(alias, cert);
 
	OutputStream out = new FileOutputStream("jssecacerts");
	ks.store(out, passphrase);
	out.close();
 
	System.out.println();
	System.out.println(cert);
	System.out.println();
	System.out.println
		("Added certificate to keystore 'jssecacerts' using alias '"
		+ alias + "'");
    }
 
    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
 
    private static String toHexString(byte[] bytes) {
	StringBuilder sb = new StringBuilder(bytes.length * 3);
	for (int b : bytes) {
	    b &= 0xff;
	    sb.append(HEXDIGITS[b >> 4]);
	    sb.append(HEXDIGITS[b & 15]);
	    sb.append(' ');
	}
	return sb.toString();
    }
 
    private static class SavingTrustManager implements X509TrustManager {
 
	private final X509TrustManager tm;
	private X509Certificate[] chain;
 
	SavingTrustManager(X509TrustManager tm) {
	    this.tm = tm;
	}
 
	public X509Certificate[] getAcceptedIssuers() {
	    throw new UnsupportedOperationException();
	}
 
	public void checkClientTrusted(X509Certificate[] chain, String authType)
		throws CertificateException {
	    throw new UnsupportedOperationException();
	}
 
	public void checkServerTrusted(X509Certificate[] chain, String authType)
		throws CertificateException {
	    this.chain = chain;
	    tm.checkServerTrusted(chain, authType);
	}
    }
 
}

将代码复制到工程中

 执行完毕没有报错会在工程下面生成jssecacerts文件

将文件放到jdk/jre/lib/security/路径下,具体试实际路径为准,我存放的位置是:/usr/local/apps/jdk1.7.0_79/jre/lib/security/jssecacerts

在调用https接口的实现类中加入以下代码,指定证书位置:

	/*
     * 设置证书。
     */
    static{
        javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
                new javax.net.ssl.HostnameVerifier(){
                    public boolean verify(String hostname,
                            javax.net.ssl.SSLSession sslSession) {
                        //域名或ip地址
                        if (hostname.equals("xxx.com")) {
                            return true;
                        }
                        return false;
                    }
                });
        System.setProperty("javax.net.ssl.trustStore", "/usr/local/apps/jdk1.7.0_79/jre/lib/security/jssecacerts");
        System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
    }

注意:hostname.equals("xxx.com")中xxx.com需要替换为Arguments中填的参数,

changeit是jdk证书的默认密码

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 使用Java调用HTTP接口的步骤如下: 1. 创建一个URL对象,指定HTTP接口的地址。 2. 打开URL连接,获取URLConnection对象。 3. 设置URLConnection对象的请求方式、超时时间等参数。 4. 发送请求,并获取服务器返回的响应结果。 5. 处理响应结果,可以将响应结果转换成字符串或其他格式。 下面是一个简单的示例代码,演示如何使用Java调用HTTP接口: ```java import java.net.*; import java.io.*; public class HttpDemo { public static void main(String[] args) throws Exception { URL url = new URL("http://example.com/api"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); if (conn.getResponseCode() != 200) { throw new RuntimeException("HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } } ``` 上面的代码使用Java的URLConnection类实现了一个简单的HTTP GET请求,并将响应结果输出到控制台。如果需要发送POST请求,可以使用URLConnection的setRequestMethod方法设置为POST,并调用URLConnection的getOutputStream方法向服务器发送请求数据。 ### 回答2: 使用Java调用HTTP接口的主要步骤如下: 1. 导入相关的类库:首先需要在Java项目中导入相关的类库,如java.net包下的URL、HttpURLConnection类等。 2. 构建URL对象:根据需要调用的HTTP接口地址,使用URL类的构造方法创建URL对象。例如,可以通过URL url = new URL("http://www.example.com/api")创建一个指向接口地址的URL对象。 3. 打开连接:通过调用URL对象的openConnection()方法,打开URL连接。这将返回一个URLConnection对象。 4. 设置请求参数:如果需要传递请求参数,可以通过调用URLConnection对象的setRequestMethod()方法设置HTTP请求方法,例如GET或POST。可以通过调用URLConnection对象的setRequestProperty()方法设置请求头参数,例如Content-Type,Authorization等。 5. 发送请求:如果是GET请求,可以直接调用URLConnection对象的connect()方法发送请求。如果是POST请求,可以先获取URLConnection对象的OutputStream,并通过写入输出流的方式发送请求参数,然后再调用connect()方法发送请求。 6. 获取响应:通过调用URLConnection对象的getResponseCode()方法获取HTTP响应的状态码,以判断请求是否成功。可以通过调用URLConnection对象的getInputStream()方法获取HTTP响应的输入流,以获取响应数据。 7. 处理响应:根据接口的具体响应数据格式,可以使用Java提供的相关类库(如JSON解析库)对响应数据进行解析和处理。 8. 关闭连接:使用完毕后,需要调用URLConnection对象的disconnect()方法关闭连接。 注意事项: - 如果接口需要进行身份认证,可以在请求头中添加Authorization参数,例如使用Basic Auth或Token等方式。 - 使用HTTPS协议时,需要进行SSL证书验证。 - 在处理大量请求时,可能需要考虑使用连接池来提高性能和资源利用率。 总结:通过以上步骤,我们可以使用Java调用HTTP接口,发送请求并处理响应,实现与其他系统进行数据交互。 ### 回答3: 使用Java调用http接口可以通过Java的网络编程功能来实现。Java提供了许多类和方法来实现http请求和接收http响应。 首先,我们可以使用Java的URL类来创建一个URL对象,指定要访问的http接口的地址。然后,我们可以使用URLConnection类的openConnection()方法打开该URL连接,并将其转换为HttpURLConnection对象。 接下来,我们可以设置HttpURLConnection对象的请求方法(GET、POST、PUT、DELETE等),设置请求头部信息(如Content-Type、Authorization等),并通过setDoOutput()方法将请求数据写入连接。 然后,我们可以使用HttpURLConnection的getOutputStream()方法获取输出流,将请求数据写入流中。如果是GET请求,可以通过HttpURLConnection的getInputStream()方法获取输入流,读取服务器的响应数据。 最后,我们可以使用BufferedReader类逐行读取服务器的响应数据,并保存在一个字符串中,或按照其它需要进行处理。 在处理http响应数据时,我们可以使用Java提供的第三方库,如Apache HttpClient和OkHttp,它们封装了更多的功能和便捷的方法,使用起来更加方便。 总的来说,使用Java调用http接口需要一些基本的编程知识和网络编程相关的类和方法。通过对Java网络编程的学习和使用,我们可以轻松地实现与http接口的交互,并处理接口返回的数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值