java模拟发送form-data的请求方式
我就废话不多说了,大家还是直接看代码吧!
packagecom.silot.test;
importorg.apache.http.HttpResponse;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.entity.mime.HttpMultipartMode;
importorg.apache.http.entity.mime.MultipartEntity;
importorg.apache.http.entity.mime.content.StringBody;
importorg.apache.http.impl.client.DefaultHttpClient;
importjava.io.BufferedReader;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.nio.charset.Charset;
publicclassTestCli
{
publicstaticvoidmain(Stringargs[])throwsException
{
MultipartEntitymultipartEntity=newMultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,"------------------------------0ea3fcae38ff",Charset.defaultCharset());
multipartEntity.addPart("skey",newStringBody("哈哈哈哈哈",Charset.forName("UTF-8")));
multipartEntity.addPart("operator",newStringBody("啦啦啦啦",Charset.forName("UTF-8")));
multipartEntity.addPart("VrfKey",newStringBody("渣渣渣",Charset.forName("UTF-8")));
multipartEntity.addPart("StatCode",newStringBody("00",Charset.forName("UTF-8")));
multipartEntity.addPart("mass_id",newStringBody("1234",Charset.forName("UTF-8")));
multipartEntity.addPart("reference_id",newStringBody("21231544",Charset.forName("UTF-8")));
HttpPostrequest=newHttpPost("http://xiefei.s1.natapp.cc/v1/withdrawCallback");
request.setEntity(multipartEntity);
request.addHeader("Content-Type","Content-Disposition:form-data;boundary=------------------------------0ea3fcae38ff");
DefaultHttpClienthttpClient=newDefaultHttpClient();
HttpResponseresponse=httpClient.execute(request);
InputStreamis=response.getEntity().getContent();
BufferedReaderin=newBufferedReader(newInputStreamReader(is));
StringBufferbuffer=newStringBuffer();
Stringline="";
while((line=in.readLine())!=null)
{
buffer.append(line);
}
System.out.println("发送消息收到的返回:"+buffer.toString());
}
}
补充知识:java模拟复杂表单post请求
java模拟复杂表单post请求
能支持文件上传
/**
*支持复杂表单,比如文件上传
*@paramformParam
*@return
*@throwsException
*/
publicstaticStringpostWithForm(FormParamformParam)throwsException{
Stringurl=formParam.getUrl();
Stringcharset="UTF-8";
Stringboundary=Long.toHexString(System.currentTimeMillis());//Justgeneratesomeuniquerandomvalue.
StringCRLF="\r\n";//Lineseparatorrequiredbymultipart/form-data.
URLConnectionconnection=newURL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","multipart/form-data;boundary="+boundary);
try(
OutputStreamoutput=connection.getOutputStream();
PrintWriterwriter=newPrintWriter(newOutputStreamWriter(output,charset),true);
){
//makebodyparam
MapbodyParam=formParam.getBodyParam();
if(null!=bodyParam){
for(Stringp:bodyParam.keySet()){
writer.append("--"+boundary).append(CRLF);
writer.append("Content-Disposition:form-data;name=\""+p+"\"").append(CRLF);
writer.append("Content-Type:text/plain;charset="+charset).append(CRLF);
writer.append(CRLF).append(bodyParam.get(p)).append(CRLF).flush();
}
}
//Sendfile.
MapfileParam=formParam.getFileParam();
if(null!=fileParam){
for(StringfileName:fileParam.keySet()){
writer.append("--"+boundary).append(CRLF);
writer.append("Content-Disposition:form-data;name=\""+fileName+"\";filename=\""
+fileParam.get(fileName).getName()+"\"").append(CRLF);
writer.append("Content-Type:"+URLConnection.guessContentTypeFromName(fileName)).append(CRLF);
writer.append("Content-Transfer-Encoding:binary").append(CRLF);
writer.append(CRLF).flush();
Files.copy(fileParam.get(fileName).toPath(),output);
output.flush();//Importantbeforecontinuingwithwriter!
writer.append(CRLF).flush();//CRLFisimportant!Itindicatesendofboundary.
}
}
//Endofmultipart/form-data.
writer.append("--"+boundary+"--").append(CRLF).flush();
}
HttpURLConnectionconn=(HttpURLConnection)connection;
ByteArrayOutputStreambout=newByteArrayOutputStream();
intlen;
byte[]buffer=newbyte[1024];
while((len=conn.getInputStream().read(buffer))!=-1){
bout.write(buffer,0,len);
}
Stringresult=newString(bout.toByteArray(),"utf-8");
returnresult;
}
FormParam封装类:
packagenet.riking.core.utils;
importjava.io.File;
importjava.util.Map;
publicclassFormParam{
privateStringurl;
// privateStringauth;
// /**
// *http请求头里的参数
// */
// privateMapheaderParam;
/**
*常规参数
*/
privateMapbodyParam;
/**
*待上传的文件参数filename和file
*/
privateMapfileParam;
publicStringgetUrl(){
returnurl;
}
publicvoidsetUrl(Stringurl){
this.url=url;
}
// publicStringgetAuth(){
// returnauth;
// }
//
// publicvoidsetAuth(Stringauth){
// this.auth=auth;
// }
//
// publicMapgetHeaderParam(){
// returnheaderParam;
// }
//
// publicvoidsetHeaderParam(MapheaderParam){
// this.headerParam=headerParam;
// }
publicMapgetBodyParam(){
returnbodyParam;
}
publicvoidsetBodyParam(MapbodyParam){
this.bodyParam=bodyParam;
}
publicMapgetFileParam(){
returnfileParam;
}
publicvoidsetFileParam(MapfileParam){
this.fileParam=fileParam;
}
}
以上这篇java模拟发送form-data的请求方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。