事实证明翻百度是没有用的,还是得自己写
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Map;
public class HttpFormData {
//url为需要请求的地址
public static String doPost(String url, Map<String, String> paramsMap, Map<String, File> fileMap) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// 解决中文乱码
ContentType contentType = ContentType.create("text/plain",Charset.forName("UTF-8"));
// params
for(Map.Entry<String, String> params : paramsMap.entrySet()){
builder.addTextBody(params.getKey(),params.getValue(),contentType);
}
// file
for(Map.Entry<String, File> file : fileMap.entrySet()){
builder.addBinaryBody(file.getKey(),file.getValue(), ContentType.MULTIPART_FORM_DATA,file.getValue().getName());
}
HttpEntity entity = builder.build();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
HttpResponse httpResponse = null;
BufferedReader in = null;
try{
httpResponse = httpclient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
if(code == 200) { //请求成功
in = new BufferedReader(new InputStreamReader(httpResponse.getEntity()
.getContent(),"utf-8"));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
System.out.println("收到的返回信息为:{}"+sb.toString());
return sb.toString();
}
}catch(IOException e){
e.printStackTrace();
}
return "error";
}
}
Comments | NOTHING