java发送http/https请求

发送http请求:

public static String sendHttpPostgetToken(String urlParam,User user)  throws IOException, KeyManagementException, NoSuchAlgorithmException {
		StringBuffer resultBuffer = null;
		HttpURLConnection con = null;
		OutputStreamWriter osw = null;
		BufferedReader br = null;
        PrintWriter pw = null;
        // 发送请求
		try {
			URL url = new URL(null, urlParam, new sun.net.www.protocol.http.Handler());
			con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("POST");
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setUseCaches(false);
            con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            con.setRequestProperty("Accept", "application/json;version=v6.3;charset=UTF-8");
			if (user != null) {
                ObjectMapper objectMapper = new ObjectMapper();
                pw = new PrintWriter(new BufferedOutputStream(con.getOutputStream()));
                pw.write(objectMapper.writeValueAsString(user));
                pw.flush();
//				Iterator<String> iteratorHeader = infoMap.keySet()
//						.iterator();
//				while (iteratorHeader.hasNext()) {
//					String key = iteratorHeader.next();
//					con.setRequestProperty(key,
//							infoMap.get(key));
//				}
			}

			// 读取返回内容
			resultBuffer = new StringBuffer();
            BufferedReader br2 = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
            String line = null;
            StringBuilder result = new StringBuilder();
            while ((line = br2.readLine()) != null) { // 读取数据
                result.append(line + "\n");
            }
            LOGGER.info(result.toString());
			LOGGER.info(con.getResponseMessage());
			LOGGER.info(con.getHeaderField("Content-Length"));
			if (StringUtils.isNotBlank(con.getHeaderField("Content-Length"))) {
				int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
					resultBuffer.append(con.getHeaderField("X-Auth-Token"));
			}

		} catch (Exception e) {
			LOGGER.error(e.getMessage(),e);
			throw new RuntimeException(e);
		} finally {
			if (osw != null) {
				try {
					osw.close();
				} catch (IOException e) {
					osw = null;
                    LOGGER.error(e.getMessage(),e);
					throw new RuntimeException(e);
				}
			}
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					br = null;
					LOGGER.error(e.getMessage(),e);
					throw new RuntimeException(e);
				}
			}
            if (pw != null) {
                try {
                    pw.close();
                } catch (Exception e) {
                    pw = null;
                    LOGGER.error(e.getMessage(),e);
                    throw new RuntimeException(e);
                }
            }
            if (con != null) {
                try {
                    con.disconnect();
                } catch (Exception e) {
                    con = null;
                    LOGGER.error(e.getMessage(),e);
                    throw new RuntimeException(e);
                }
            }

		}

		return resultBuffer.toString();
	}

发送HTTPS请求:

public static String sendHttpsPost(String urlParam,Map<String, String> infoMap,List<FusionComputeParam> paramList)  throws IOException, KeyManagementException, NoSuchAlgorithmException {
		HttpsURLConnection.setDefaultHostnameVerifier(new HttpClientHelper().new NullHostNameVerifier());
		SSLContext sc = SSLContext.getInstance("TLS");
		sc.init(null, trustAllCerts, new SecureRandom());
		HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

		StringBuffer resultBuffer = null;
		HttpsURLConnection con = null;
		OutputStreamWriter osw = null;
		BufferedReader br = null;

		// 发送请求
		try {
			URL url = new URL(urlParam);
			con = (HttpsURLConnection) url.openConnection();
			con.setRequestMethod("POST");
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setUseCaches(false);
			//放在消息头里面
			if (infoMap != null) {
				Iterator<String> iteratorHeader = infoMap.keySet()
						.iterator();
				while (iteratorHeader.hasNext()) {
					String key = iteratorHeader.next();
					con.setRequestProperty(key,
							infoMap.get(key));
				}
			}
			con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
			con.setRequestProperty("Accept", "application/json;version=v6.3;charset=UTF-8");

			//放在消息体里面(Body Data)
				osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
				if(null != paramList && paramList.size() > 0){
					osw.write(JSONUtil.toJsonStr(paramList));
				}
				osw.flush();


			// 读取返回内容
			resultBuffer = new StringBuffer();
			if (StringUtils.isNotBlank(con.getHeaderField("Content-Length"))) {
				int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
				if (contentLength > 0 &&(null != paramList && paramList.size() > 0)) {
					br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
					String temp;
					while ((temp = br.readLine()) != null) {
						resultBuffer.append(temp);
					}
				}else{
					resultBuffer.append(con.getHeaderField("X-Auth-Token"));
				}
			}

		} catch (Exception e) {
			LOGGER.error(e.getMessage(),e);
			throw new RuntimeException(e);
		} finally {
			if (osw != null) {
				try {
					osw.close();
				} catch (IOException e) {
					osw = null;
					throw new RuntimeException(e);
				} finally {
					if (con != null) {
						con.disconnect();
						con = null;
					}
				}
			}
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					br = null;
					LOGGER.error(e.getMessage(),e);
					throw new RuntimeException(e);
				} finally {
					if (con != null) {
						con.disconnect();
						con = null;
					}
				}
			}
		}

		return resultBuffer.toString();
	}
static TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
		@Override
		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			// TODO Auto-generated method stub
		}

		@Override
		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			// TODO Auto-generated method stub
		}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			// TODO Auto-generated method stub
			return null;
		}
	}
	};

	public class NullHostNameVerifier implements HostnameVerifier {
		/*
		 * (non-Javadoc)
		 *
		 * @see javax.net.ssl.HostnameVerifier#verify(java.lang.String,
		 * javax.net.ssl.SSLSession)
		 */
		@Override
		public boolean verify(String arg0, SSLSession arg1) {
			// TODO Auto-generated method stub
			return true;
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值