Last active
January 3, 2017 02:57
-
-
Save imwower/624651eb952f1a2bd1d74607278ef143 to your computer and use it in GitHub Desktop.
java使用apache http client发送get和post请求;支持文件上传和ssl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com; | |
import org.apache.http.HttpEntity; | |
import org.apache.http.HttpResponse; | |
import org.apache.http.NameValuePair; | |
import org.apache.http.client.entity.UrlEncodedFormEntity; | |
import org.apache.http.client.methods.CloseableHttpResponse; | |
import org.apache.http.client.methods.HttpGet; | |
import org.apache.http.client.methods.HttpPost; | |
import org.apache.http.conn.ssl.SSLConnectionSocketFactory; | |
import org.apache.http.conn.ssl.SSLContextBuilder; | |
import org.apache.http.conn.ssl.TrustStrategy; | |
import org.apache.http.entity.ContentType; | |
import org.apache.http.entity.StringEntity; | |
import org.apache.http.entity.mime.MultipartEntityBuilder; | |
import org.apache.http.impl.client.CloseableHttpClient; | |
import org.apache.http.impl.client.HttpClients; | |
import org.apache.http.message.BasicNameValuePair; | |
import org.apache.http.util.EntityUtils; | |
import org.codehaus.jackson.map.ObjectMapper; | |
import javax.net.ssl.SSLContext; | |
import java.io.BufferedReader; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.security.KeyManagementException; | |
import java.security.KeyStoreException; | |
import java.security.NoSuchAlgorithmException; | |
import java.security.cert.CertificateException; | |
import java.security.cert.X509Certificate; | |
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
/** | |
* Created by george on 2017/1/3. | |
*/ | |
/** | |
* 使用apache http client发送get和post请求;支持文件上传 | |
*/ | |
public class RestClient { | |
private static SSLConnectionSocketFactory sslConnectionSocketFactory; | |
{ | |
try { | |
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { | |
//信任所有 | |
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { | |
return true; | |
} | |
}).build(); | |
sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext); | |
} catch (NoSuchAlgorithmException e) { | |
e.printStackTrace(); | |
} catch (KeyManagementException e) { | |
e.printStackTrace(); | |
} catch (KeyStoreException e) { | |
e.printStackTrace(); | |
} | |
} | |
public static CloseableHttpClient createHttpClient() { | |
return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build(); | |
} | |
public static String SendGet(String url) throws Exception { | |
return sendGet(url, null); | |
} | |
public static String sendGet(String url, Map<String, Object> params) throws Exception { | |
String result = ""; | |
BufferedReader reader = null; | |
CloseableHttpClient httpClient = createHttpClient(); | |
String fullUrl = url + generateParam(params); | |
HttpGet httpGet = new HttpGet(fullUrl); | |
CloseableHttpResponse response = httpClient.execute(httpGet); | |
HttpEntity entity = response.getEntity(); | |
if (entity != null) { | |
result = EntityUtils.toString(entity); | |
} | |
return result; | |
} | |
/** | |
* 发送post请求;上传文件时,map的value为File对象 | |
* | |
* @param url | |
* @param contentType | |
* @param params | |
* @return | |
* @throws Exception | |
*/ | |
public static String sendPost(String url, ContentType contentType, Map<String, Object> params) throws Exception { | |
String result = ""; | |
CloseableHttpClient closeableHttpClient = createHttpClient(); | |
HttpPost httpPost = new HttpPost(url); | |
HttpEntity httpEntity = null; | |
MultipartEntityBuilder builder = null; | |
if (contentType.equals(ContentType.APPLICATION_JSON)) { | |
ObjectMapper mapper = new ObjectMapper(); | |
httpEntity = new StringEntity(mapper.writeValueAsString(params)); | |
} else if (contentType.equals(ContentType.APPLICATION_FORM_URLENCODED)) { | |
if (params != null && !params.isEmpty()) { | |
List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size()); | |
for (Map.Entry<String, Object> entry : params.entrySet()) { | |
Object value = entry.getValue(); | |
if (value != null) { | |
pairs.add(new BasicNameValuePair(entry.getKey(), value.toString())); | |
} | |
} | |
httpEntity = new UrlEncodedFormEntity(pairs); | |
} | |
} else if (contentType.equals(ContentType.MULTIPART_FORM_DATA)) { | |
if (params != null && !params.isEmpty()) { | |
builder = MultipartEntityBuilder.create(); | |
for (Map.Entry<String, Object> entry : params.entrySet()) { | |
Object value = entry.getValue(); | |
if (value != null) { | |
if (value instanceof File) { | |
File file = (File) value; | |
builder.addBinaryBody(entry.getKey(), new FileInputStream(file), org.apache.http.entity.ContentType.APPLICATION_OCTET_STREAM, file.getName()); | |
} else { | |
builder.addTextBody(entry.getKey(), value.toString(), org.apache.http.entity.ContentType.MULTIPART_FORM_DATA); | |
} | |
} | |
} | |
httpEntity = builder.build(); | |
} | |
} | |
httpPost.setEntity(httpEntity); | |
HttpResponse res = closeableHttpClient.execute(httpPost); | |
HttpEntity entity = res.getEntity(); | |
result = EntityUtils.toString(entity); | |
return result; | |
} | |
/** | |
* 生成请求的参数;name=value&name2=value2 | |
* | |
* @param params | |
* @return | |
*/ | |
private static String generateParam(Map<String, Object> params) { | |
if (params == null || params.size() == 0) { | |
return ""; | |
} | |
StringBuilder builder = new StringBuilder(); | |
for (Map.Entry<String, Object> key : params.entrySet()) { | |
builder.append(key.getKey()).append("=").append(key.getValue()).append("&"); | |
} | |
if (builder.length() > 0) { | |
builder.setLength(builder.length() - 1); | |
} | |
return builder.toString(); | |
} | |
public static void main(String[] arg) { | |
try { | |
String url = "http://localhost:9999/home/upload"; | |
Map<String, Object> map = new HashMap<String, Object>() { | |
{ | |
File file = new File("file.txt"); | |
put("file", file); | |
put("filename", "abc"); | |
} | |
}; | |
String result = sendPost(url, ContentType.MULTIPART_FORM_DATA, map); | |
} catch (Exception e) { | |
System.out.println(e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment