添加apache的httpClient依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>

/**
* 用于进行https请求的httpClient
* @author mrxiab
* @date 2017/9/10 17:57
* @ClassName: SSLClient
* @Description: TODO
*
*/
class SSLClient extends DefaultHttpClient {
public SSLClient() throws Exception{
super();
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {

public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}

public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
}
}

public class HttpUtil {

public static String sendGet(String url, String param) throws Exception{
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line+"\n";
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}

/**
2 * get请求,参数放在map里
3 * @param url 请求地址
4 * @param map 参数map
5 * @return 响应
6 */
public static String getMap(String url,Map<String,String> map)
{
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
for(Map.Entry<String,String> entry : map.entrySet())
{
pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}
CloseableHttpResponse response = null;
try {
URIBuilder builder = new URIBuilder(url);
builder.setParameters(pairs);
HttpGet get = new HttpGet(builder.build());
response = httpClient.execute(get);
if(response != null && response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
result = entityToString(entity);
}
return result;
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
httpClient.close();
if(response != null)
{
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

return null;
}


private static String entityToString(HttpEntity entity) throws IOException {
String result = null;
if(entity != null)
{
long lenth = entity.getContentLength();
if(lenth != -1 && lenth < 2048)
{
result = EntityUtils.toString(entity,"UTF-8");
}else {
InputStreamReader reader1 = new InputStreamReader(entity.getContent(), "UTF-8");
CharArrayBuffer buffer = new CharArrayBuffer(2048);
char[] tmp = new char[1024];
int l;
while((l = reader1.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
result = buffer.toString();
}
}
return result;
}

public static String doPost(String url,Map<String, String> map){
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try{
httpClient = new SSLClient();
httpPost = new HttpPost(url);
List<NameValuePair> list=new ArrayList<NameValuePair>();
Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String,String> elem = (Map.Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(),String.valueOf(elem.getValue())));
}
if(list.size() > 0){
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"UTF-8");
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode == 200){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity,"UTF-8");
}
}
if(statusCode == 302){
Header locationHeader = response.getFirstHeader("Location");
if (locationHeader != null) {
result = locationHeader.getValue();
}
}
}catch(Exception ex){
ex.printStackTrace();
}
return result;
}
public static String doPostJson(String url, String params) throws Exception {
String charset = "UTF-8";
RequestConfig config = RequestConfig.custom().setConnectTimeout(600000).setSocketTimeout(600000).build();
CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
int stateCode = 0;
String content = null;
CloseableHttpResponse response = null;
try {

HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type","application/json");
httpPost.setEntity(new StringEntity(params, charset));
response = httpClient.execute(httpPost);
stateCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (entity != null) {
content = EntityUtils.toString(entity, charset);
}else{
return null;
}
EntityUtils.consume(entity);
} catch (Exception e) {

e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
}
}
if(httpClient!=null){
try {
httpClient.close();
} catch (IOException e) {
}
}
httpClient=null;
response = null;
}
if (stateCode != 200) {
throw new RuntimeException("HttpClient,error status code :" + stateCode);
}
return content;

}
}



posted on 2019-03-22 16:07  Mr.xiab  阅读(656)  评论(0编辑  收藏  举报