http与https请求

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;

/**
 * httpclient 无信任证书使用https
 * @author qtt
 *
 */
public class MySSLProtocolSocketFactory implements ProtocolSocketFactory {

	private SSLContext sslcontext = null;   
	   
	  private SSLContext createSSLContext() {   
	      SSLContext sslcontext=null;   
	      try {   
	          sslcontext = SSLContext.getInstance("SSL");   
	          sslcontext.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());   
	      } catch (NoSuchAlgorithmException e) {   
	          e.printStackTrace();   
	      } catch (KeyManagementException e) {   
	          e.printStackTrace();   
	      }   
	      return sslcontext;   
	  }   
	   
	  private SSLContext getSSLContext() {   
	      if (this.sslcontext == null) {   
	          this.sslcontext = createSSLContext();   
	      }   
	      return this.sslcontext;   
	  }   
	   
	  public Socket createSocket(Socket socket, String host, int port, boolean autoClose)   
	          throws IOException, UnknownHostException {   
	      return getSSLContext().getSocketFactory().createSocket(   
	              socket,   
	              host,   
	              port,   
	              autoClose   
	          );   
	  }   
	  
	  public Socket createSocket(String host, int port) throws IOException,   
	          UnknownHostException {   
	      return getSSLContext().getSocketFactory().createSocket(   
	              host,   
	              port   
	          );   
	  }   
	   
	   
	  public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort)   
	          throws IOException, UnknownHostException {   
	      return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);   
	  }   
	  
	  public Socket createSocket(String host, int port, InetAddress localAddress,   
	          int localPort, HttpConnectionParams params) throws IOException,   
	          UnknownHostException, ConnectTimeoutException {   
	      if (params == null) {   
	          throw new IllegalArgumentException("Parameters may not be null");   
	      }   
	      int timeout = params.getConnectionTimeout();   
	      SocketFactory socketfactory = getSSLContext().getSocketFactory();   
	      if (timeout == 0) {   
	          return socketfactory.createSocket(host, port, localAddress, localPort);   
	      } else {   
	          Socket socket = socketfactory.createSocket();   
	          SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);   
	          SocketAddress remoteaddr = new InetSocketAddress(host, port);   
	          socket.bind(localaddr);   
	          socket.connect(remoteaddr, timeout);   
	          return socket;   
	      }   
	  }   
	   
	  //自定义私有类   
	  private static class TrustAnyTrustManager implements X509TrustManager {   
	      
	  
	      public X509Certificate[] getAcceptedIssuers() {   
	          return new X509Certificate[]{};   
	      }

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

		@Override
		public void checkServerTrusted(
				java.security.cert.X509Certificate[] chain, String authType)
				throws java.security.cert.CertificateException {
		}   
	  }     
	  
	  
	}  





import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.lang.StringUtils;

import app.cn.qtt.cmbase.util.Base64;
import app.cn.qtt.cmbase.util.MySSLProtocolSocketFactory;
import app.cn.qtt.hangup.common.CacheConstants;



public class HttpDoPost {

	
	public static String doPost(String url, RequestEntity entity, Header[] headers) throws Exception {
		HttpClient httpClient = new HttpClient();
		PostMethod post = new PostMethod(url);
		post.setRequestEntity(entity);
		for (Header header : headers) {
			post.setRequestHeader(header);
		}
		int status = httpClient.executeMethod(post);
		Header[] hs = post.getResponseHeaders();
		for (Header header : hs) {
			System.out.println(header.getName()+":"+header.getValue());
		}
		if (status != HttpStatus.SC_OK) {
			return post.getResponseBodyAsString();
		}
		return post.getResponseBodyAsString();
	}
	
	public static String doPostSSL(String url, RequestEntity entity, Header[] headers) throws Exception {
		HttpClient httpClient = new HttpClient();
		Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443);   
		Protocol.registerProtocol("https", myhttps);  
		PostMethod post = new PostMethod(url);
		post.setRequestEntity(entity);
		for (Header header : headers) {
			post.setRequestHeader(header);
		}
		int status = httpClient.executeMethod(post);
		Header[] hs = post.getResponseHeaders();
		for (Header header : hs) {
			System.out.println(header.getName()+":"+header.getValue());
		}
		if (status != HttpStatus.SC_OK) {
			return post.getResponseBodyAsString();
		}
		return post.getResponseBodyAsString();
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
HttpURLConnection是Java标准库提供的用于发送HTTPHTTPS请求的类,可以用来获取Web资源,以及与服务器进行通信。下面是发送HTTPHTTPS请求的示例代码: ### 发送HTTP请求 ```java import java.net.*; import java.io.*; public class HttpURLConnectionDemo { public static void main(String[] args) throws Exception { URL url = new URL("http://www.example.com/"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } } ``` ### 发送HTTPS请求 ```java import java.net.*; import java.io.*; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; public class HttpsURLConnectionDemo { public static void main(String[] args) throws Exception { URL url = new URL("https://www.example.com/"); HttpsURLConnection.setDefaultHostnameVerifier(new NullHostnameVerifier()); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } private static class NullHostnameVerifier implements HostnameVerifier { public boolean verify(String hostname, SSLSession session) { return true; } } private static class NullTrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } } ``` 需要注意的是,发送HTTPS请求时需要进行证书验证,但这里我们使用了一个自定义的NullTrustManager类,它不对证书进行任何验证。在实际应用中,不建议使用这种方式,应该使用正确的证书验证机制来保证通信的安全性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丵鹰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值