package cn.com.cetc16.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.http.HttpEntity;
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.HttpPost;
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;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
public class PostUtil {
private static final String CHARSET = "UTF-8";
public static String post(String url, String params) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
StringEntity sEntity = new StringEntity(params, CHARSET);
httpPost.setEntity(sEntity);
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity, CHARSET);
}
} finally {
response.close();
httpClient.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
public static String postObject(String url, Map<String,Object> parammap) {
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(url);
// 创建参数队列
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> entry : parammap.entrySet()) {
formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
// 调用接口返回的字符串
return EntityUtils.toString(entity, "UTF-8");
}
} finally {
response.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
public static String postJson(String url, String json){
return postJSONWithHeaders(url, json, null);
}
public static String postJSONWithHeaders(String url, String json, Map<String, String> headers) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
StringEntity sEntity = new StringEntity(json, CHARSET);
httpPost.setEntity(sEntity);
httpPost.setHeader("Content-Type","application/json;charset=utf-8");
if (headers != null) {
for (String key : headers.keySet()) {
httpPost.setHeader(key, headers.get(key));
}
}
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity, CHARSET);
}
} finally {
response.close();
httpClient.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
public static String post(String url, Map<String,String> params) {
return postForm(url, params, null);
}
public static String postForm(String url, Map<String, String> params, String contentType) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
if (contentType != null) {
httpPost.setHeader("Content-Type",contentType);
}
List<NameValuePair> nameValuePairs = new LinkedList<>();
for (String key : params.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
}
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs,CHARSET);
httpPost.setEntity(urlEncodedFormEntity);
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity, CHARSET);
}
} finally {
response.close();
httpClient.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
public static String postFormData(String url, Map<String, String> params) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type","application/form-data");
List<NameValuePair> nameValuePairs = new LinkedList<>();
for (String key : params.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
}
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs,CHARSET);
httpPost.setEntity(urlEncodedFormEntity);
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity, CHARSET);
}
} finally {
response.close();
httpClient.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
public static String postXWwwFormUrlencoded(String url, Map<String, String> params) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type","application/x-www-form-urlencoded");
List<NameValuePair> nameValuePairs = new LinkedList<>();
for (String key : params.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
}
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs,CHARSET);
httpPost.setEntity(urlEncodedFormEntity);
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity, CHARSET);
}
} finally {
response.close();
httpClient.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
/*
* map to key=mXUDwrkUNzqAgV43WBRV&value=cmoQhx3rE6tizIzqeTgJ
*/
public static String mapToString(Map<String,String> reqMap){
String result = "";
if (reqMap ==null){
return result;
}else{
Set<String> keySet = reqMap.keySet();
for (String key : keySet) {
String value = reqMap.get(key);
if (value==null){
value="";
}
if (result ==null || ("").equals(result)){
result = result + key+"="+value;
}else {
result = result +"&"+ key+"="+value;
}
}
}
return result;
}
/*
* 发送文件
*/
public static JSONObject sendPostWithFile(MultipartFile file, HashMap<String, Object> map,String fileOCRUrl) {
DataOutputStream out = null;
DataInputStream in = null;
final String newLine = "\r\n";
final String prefix = "--";
JSONObject json = null;
try {
URL url = new URL(fileOCRUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
String BOUNDARY = "-------KingKe0520a";
conn.setRequestMethod("POST");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
out = new DataOutputStream(conn.getOutputStream());
// 添加参数file
// File file = new File(filePath);
StringBuilder sb1 = new StringBuilder();
sb1.append(prefix);
sb1.append(BOUNDARY);
sb1.append(newLine);
sb1.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"" + newLine);
sb1.append("Content-Type:application/octet-stream");
sb1.append(newLine);
sb1.append(newLine);
out.write(sb1.toString().getBytes());
// in = new DataInputStream(new FileInputStream(file));
in = new DataInputStream(file.getInputStream());
byte[] bufferOut = new byte[1024];
int bytes = 0;
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
out.write(newLine.getBytes());
StringBuilder sb = new StringBuilder();
int k = 1;
for (String key : map.keySet()) {
if (k != 1) {
sb.append(newLine);
}
sb.append(prefix);
sb.append(BOUNDARY);
sb.append(newLine);
sb.append("Content-Disposition: form-data;name=" + key + "");
sb.append(newLine);
sb.append(newLine);
sb.append(map.get(key));
out.write(sb.toString().getBytes());
sb.delete(0, sb.length());
k++;
}
byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(end_data);
out.flush();
// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
StringBuffer resultStr = new StringBuffer();
while ((line = reader.readLine()) != null) {
resultStr.append(line);
}
json = (JSONObject)JSONObject.parse(resultStr.toString());
} catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return json;
}
public static void main(String[] args) throws FileNotFoundException {
HashMap<String, Object> parammap = new HashMap<>();
parammap.put("postdata","access_token=WJVgPO3KEce3PVn4QM8TGum6BtaaZ64C");
File file = new File("F:\\mr\\文档\\胡萝卜.jpg");
FileItem fileItem = MultipartFileUtil.getMultipartFile(file, "胡萝卜.jpg");
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
JSONObject jsonObject = sendPostWithFile(multipartFile, parammap,"http://58.216.151.154:7203/cqamr_data_ws/fmarket_btyetourl.action");
System.out.println(jsonObject);
// Map<String,Object> parammap = new HashMap<>();
// parammap.put("access_token","access_token=WJVgPO3KEce3PVn4QM8TGum6BtaaZ64C");
// String s = postObject("http://58.216.151.154:7203/cqamr_data_ws/fmarket_btyetourl.action", parammap);
// Map<String,String> params = new HashMap<>();
// params.put("postdata","key=mXUDwrkUNzqAgV43WBRV&value=cmoQhx3rE6tizIzqeTgJ");
// params.put("postdata","value=cmoQhx3rE6tizIzqeTgJ&key=mXUDwrkUNzqAgV43WBRV");
// String s = postXWwwFormUrlencoded("http://58.216.151.154:7203/cqamr_data_ws/fmarket_getAccessToken.action", params);
// System.out.println(s);
// Map<String,String> params = new HashMap<>();
// params.put("key","mXUDwrkUNzqAgV43WBRV");
// params.put("value","cmoQhx3rE6tizIzqeTgJ");
// String s1 = mapToString(params);
// System.out.println(s1);
// Map<String,String> params1 = new HashMap<>();
// params.put("postdata",s1);
// String s = postXWwwFormUrlencoded("http://58.216.151.154:7203/cqamr_data_ws/fmarket_getAccessToken.action", params1);
// System.out.println(s);
}
}
postutil发送文件
最新推荐文章于 2025-06-18 10:31:06 发布