在HttpClient还没有被废弃之前了,感觉模拟表单提交还是比较简单的,因为有MultipartEntityBuilder的支持。看下面代码:
private String uploadFile(String url, HttpEntity entity) {
HttpClient httpClient=new DefaultHttpClient();// 客户端 HTTP 请求
httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);// 设置连接超时时间
httpClient.getParams().setParameter("charset", HTTP.UTF_8);
HttpPost httpPost = new HttpPost(url);//创建 HTTP POST 请求
//httpPost.addHeader("Content-Type", "text/html");
httpPost.addHeader("charset", HTTP.UTF_8);
// try {
// httpPost.setEntity(new StringEntity(entity.toString(), HTTP.UTF_8));
// } catch (UnsupportedEncodingException e1) {
// e1.printStackTrace();
// }
httpPost.setEntity(entity);
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//获取服务器返回信息
System.out.println("--------------------->result");
HttpEntity httpResponseEntity = httpResponse.getEntity();
String json = EntityUtils.toString(httpResponseEntity,"UTF-8");
System.out.println(json);
return json;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ConnectTimeoutException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpClient != null && httpClient.getConnectionManager() != null) {
httpClient.getConnectionManager().shutdown();
}
}
return null;
}
entity的build方式—–MultipartEntityBuilder,设置文本域和文件域
public String getResult(String user,String actionName,String id,ArrayList<File> files,String type)throws Exception{
String url =Constant.employeeURL+actionName;//请求url
System.out.println(url);
MultipartEntityBuilder builder =MultipartEntityBuilder.create();
builder.setCharset(Charset.forName(HTTP.UTF_8));//设置请求的编码格式
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//设置浏览器的兼容模式
ContentType contentType =ContentType.create(HTTP.PLAIN_TEXT_TYPE,HTTP.UTF_8);
// JSONObject jsonObject =new JSONObject();
// jsonObject.put("user", user);
// jsonObject.put("picture_id", picid);
// jsonObject.put("type", type);
builder.addTextBody("id",id, contentType);
builder.addTextBody("user",user, contentType);
// builder.addTextBody("picture_id",jsonObject.toString(), contentType);
// int count=0;
for(File file:files){
builder.addBinaryBody("files", file);
System.out.println("--------------"+file.getTotalSpace());
// count++;
}
HttpEntity entity =builder.build();//生成HTTP POST实体
System.out.println("生成的 HPPT POST实体++++++"+entity);
String result=uploadFile(url,entity);
return result;
}
HttpURLConnection模拟表单提交,需要去拼装请求头,完全模拟web的提交方式,看下面:
模拟代码:
/**
* 直接通过 HTTP 协议提交数据到服务器,实现表单提交功能。
* @param user 用户名
* @param actionName 上传方法名
* @param id id
* @param files 上传文件信息
* @return 返回请求结果
*/
public String post(String user,String actionName,String id,ArrayList<File> files) {
String actionUrl =Constant.employeeURL+actionName;
System.out.println(actionUrl);
HttpURLConnection conn = null;
DataOutputStream output = null;
BufferedReader input = null;
try {
URL url = new URL(actionUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(120000);
conn.setDoInput(true); // 允许输入
conn.setDoOutput(true); // 允许输出
conn.setUseCaches(false); // 不使用Cache
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
conn.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Content-Type", multipart_form_data + "; boundary=" + boundary);
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36");
conn.connect();
output = new DataOutputStream(conn.getOutputStream());
addText(user, id, output); // 添加文本字段
addImage(files, output); // 添加图片
output.writeBytes(lineStart + boundary + lineStart + lineEnd);// 数据结束标志
output.flush();
int code = conn.getResponseCode();
System.out.println("**************result"+code);
if(code == 200) {
System.out.println("**************result");
input = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String oneLine;
while((oneLine = input.readLine()) != null) {
response.append(oneLine + lineEnd);
}
return response.toString();
}else{
return null;
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
// 统一释放资源
try {
if(output != null) {
output.close();
}
if(input != null) {
input.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
if(conn != null) {
conn.disconnect();
}
}
}
private void addText(String user,String id,DataOutputStream output) {
StringBuilder sb = new StringBuilder();
sb.append(lineStart + boundary + lineEnd);
sb.append("Content-Disposition: form-data; name=\"id\"" + lineEnd);
sb.append(lineEnd);
sb.append(id + lineEnd);
sb.append(lineStart + boundary + lineEnd);
sb.append("Content-Disposition: form-data; name=\"user\"" + lineEnd);
sb.append(lineEnd);
sb.append(user + lineEnd);
try {
output.writeBytes(sb.toString());// 发送表单字段数据
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println("**************result" + sb);
}
private void addImage(ArrayList<File> files, DataOutputStream output) {
for(File file : files) {
StringBuilder split = new StringBuilder();
split.append(lineStart + boundary + lineEnd);
split.append("Content-Disposition: form-data; name=\"" + "files" + "\"; filename=\"" + file.getName() + "\"" + lineEnd);
split.append("Content-Type: " + "image/jpeg" + lineEnd);
split.append(lineEnd);
System.out.println("**************result" + split);
try {
// 发送图片数据
output.writeBytes(split.toString());
FileInputStream fis = new FileInputStream(file);
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1)
{
output.write(b, 0, n);
}
fis.close();
output.writeBytes(lineEnd);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
相关的常量:
String multipart_form_data = "multipart/form-data";
String lineStart = "--";
String boundary = "****************ef5fH38L0hL9DIO"; // 数据分隔符
String lineEnd ="\r\n";