发送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;
}
}