1.http post请求传参数+文件
import java.nio.charset.Charset;
import java.util.*;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
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.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
/**
*
* @Description:
* @Author:ay
* @Date:2020/8/26
*/
public class HttpFileUtils {
private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
private static final CloseableHttpClient httpclient = HttpClients.createDefault();
private static final String userAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36";
/** * 发送HttpPost请求,参数为文件,适用于微信上传素材 * * @param url * 请求地址 * @param file * 上传的文件 * @return 返回字符串 * @throws IOException * @throws ClientProtocolException */
public static String sendPost(String url, String method,Map<String, Object> paramMap, List<File> files) throws IOException {
// 20190519 wangwei 修改参数逻辑: 参数级别url,paramMap,attributes,前面已经出现的,后面设置的无效
// 定义包含的参数
// 提出原本url里面的参数
List<String> existParamList = getUrlParam(url);
StringBuffer params = new StringBuffer();
// url参数处理
if (paramMap != null && paramMap.size() > 0) {
Iterator<Map.Entry<String, Object>> iter = paramMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Object> entry = iter.next();
if (!existParamList.contains(entry.getKey())) {
params.append(entry.getKey() + "=" + entry.getValue() + "&");
existParamList.add(entry.getKey());
}
}
}
// 获取request自带参数
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null) {
HttpServletRequest request = attributes.getRequest();
Enumeration<String> enuer = request.getParameterNames();
while (enuer.hasMoreElements()) {
String paraName = (String) enuer.nextElement();
// 参数(如果需要得统一编码处理)需要编码统一处理,防止特殊字符情况
if (!existParamList.contains(paraName)) {
params.append(paraName + "=" + request.getParameter(paraName) + "&");
existParamList.add(paraName);
}
}
}
// 将request自带参数和url参数拼接在url后面
if (params.length() > 1) {
if (url.contains("?")) {
url = url + "&" + params.deleteCharAt(params.length() - 1);
} else {
url = url + "?" + params.deleteCharAt(params.length() - 1);
}
}
String result = null;
HttpPost httpPost = new HttpPost(url);
// 防止被当成攻击添加的
httpPost.setHeader("User-Agent", userAgent);
// 实例化参数对象
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
multipartEntity.setCharset(Charset.forName("utf-8"));
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//multifile 转file,存file
for(File file :files){
multipartEntity.addBinaryBody("files",file);
// httpPost.setHeader( "Content-Disposition", "attachment;filename=" + new String( file.getName().getBytes("GBK"), "ISO8859-1" ) );
}
httpPost.setEntity(multipartEntity.build());
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
} catch (IOException e) {
log.error(e.getMessage());
} finally {
// 关闭CloseableHttpResponse
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage());
}
}
}
return result;
}
/**
* 获取url里面参数名称
*
* @param url 地址
* @return 参数名称
* @author wangwei
* @date 2019年5月19日
*/
private static List<String> getUrlParam(String url) {
// 定义包含的参数
List<String> existParam = new ArrayList<>();
// 提出原本url里面的参数
if (url.contains("?")) {
String urlParam = url.split("\\?")[1];
String[] urlParamS = urlParam.split("&");
for (String up : urlParamS) {
existParam.add(up.split("=")[0]);
}
}
return existParam;
}
public static File MutifileToFile(MultipartFile multipartFile ){
//文件上传前的名称
String fileName = multipartFile.getOriginalFilename();
File file = new File(fileName);
OutputStream out = null;
try{
//获取文件流,以文件流的方式输出到新文件
// InputStream in = multipartFile.getInputStream();
out = new FileOutputStream(file);
byte[] ss = multipartFile.getBytes();
for(int i = 0; i < ss.length; i++){
out.write(ss[i]);
}
}catch(IOException e){
e.printStackTrace();
}finally {
if (out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return file;
}
}
2.Http post 传报文格式的数据(JSON格式数据)
/**
*
* @Description:
* @Author:ay
* @Date:2020/9/5
*/
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
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.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
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;
public class HttptestUtil {
public static String doGet(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doGet(String url) {
return doGet(url, null);
}
public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
public static String doPost(String url) {
return doPost(url, null);
}
public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
}
3.post 解析WebService xml 格式数据
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* @author songwen
* @Title: WebServiceUtils
* @Description: TODO
* @date 2018/8/30
*/
public class WebServiceUtils {
/**
* 判断URL是否可达
*
* @param url 待判断的URL
* @return true: 可达 false: 不可达
*/
public static boolean urlIsReach(String url) {
if (url == null) {
return false;
}
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
return true;
}
} catch (Exception e) {
return false;
}
return false;
}
public static boolean urlIsReach(String url, int receiveTimeOut, int connectTimeOut) {
if (url == null) {
return false;
}
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setReadTimeout(receiveTimeOut);
connection.setConnectTimeout(connectTimeOut);
if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
return true;
}
} catch (Exception e) {
return false;
}
return false;
}
/**
* 请求webservice服务
*
* @param url 地址
* @param method 方法名
* @param map 参数
* @return
* @throws Exception
*/
public static String sendRequest(String url, String method, Map<String, Object> map) throws Exception {
return sendRequest(url, method, null, null, map.values().toArray());
}
/**
* 请求webservice服务
*
* @param url 地址
* @param method 方法名
* @param map 参数
* @return
* @throws Exception
*/
public static String sendRequest(String url, String method, Long connectTimeOut, Long receiveTimeOut, Map<String, Object> map) throws Exception {
return sendRequest(url, method, connectTimeOut, receiveTimeOut, map.values().toArray());
}
/**
* 请求webservice服务
*
* @param url 地址
* @param method 方法名
* @param connectTimeOut 连接超时时间
* @param receiveTimeOut 接收超时时间
* @param params 参数
* @return
* @throws Exception
*/
public static String sendRequest(String url, String method, Long connectTimeOut, Long receiveTimeOut, Object... params) throws Exception {
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
Client client = dcf.createClient(url);
HTTPClientPolicy policy = new HTTPClientPolicy();
HTTPConduit conduit = (HTTPConduit) client.getConduit();
if (connectTimeOut != null) {
policy.setConnectionTimeout(connectTimeOut);
}
if (receiveTimeOut != null) {
policy.setReceiveTimeout(receiveTimeOut);
}
conduit.setClient(policy);
// Object[] invoke = client.invoke(method, params);
Object[] objects = client.invoke(method, params);
String result = GsonUtils.beanTojson(objects[0]);
// System.out.println(GsonUtils.beanTojson(objects[0]));
// client.close();
return result;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)