基本信息
源码名称:java模仿http表单提交数据(含文件上传)实例源码
源码大小:4.18M
文件格式:.zip
开发语言:Java
更新时间:2019-09-24
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
java模仿http表单提交数据、模仿http表单上传文件示例
package com.snca.cloudsign.main;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class CloudSignRestUtil {
/**
* 正常数据请求
* @param url
* @param data
* @return
*/
public static String commDataRequest(String url,String data)throws ClientProtocolException,ParseException,IOException{
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
httpClient = HttpClients.createDefault();
HttpEntity entity = new StringEntity(data,Consts.UTF_8);
httpPost.setEntity(entity);
httpPost.addHeader("Content-Type", "application/json");
httpPost.setEntity(entity);
try {
response = httpClient.execute(httpPost);
return EntityUtils.toString(response.getEntity(),Charset.forName("UTF-8"));
}finally {
if(response != null){
response.close();
}
if(httpClient != null){
httpClient.close();
}
}
}
/**
* 带文件的数据接口请求
* @param url
* @param data
* @return
*/
public static String fileDataRequest(String url,String data,File pdfFile)throws ClientProtocolException,ParseException,IOException{
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try{
httpClient = HttpClients.createDefault();
StringBody requestData = new StringBody(data, ContentType.create(
"text/plain", Consts.UTF_8));
FileBody bin = new FileBody(pdfFile);
HttpEntity entity = MultipartEntityBuilder.create()
.addPart("pdfFile", bin)
.addPart("requestData", requestData)
.build();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
// 发起请求 并返回请求的响应
response = httpClient.execute(httpPost);
// 获取响应对象
HttpEntity resEntity = response.getEntity();
String responseStr = EntityUtils.toString(response.getEntity(),Charset.forName("UTF-8"));
// 销毁
EntityUtils.consume(resEntity);
return responseStr;
}finally {
if(response != null){
response.close();
}
if(httpClient != null){
httpClient.close();
}
}
}
}