您的位置:首页 > 编程语言 > Java开发

java模拟表单提交数据

2017-11-09 12:09 369 查看
demo地址 https://gitee.com/yuhaifei/PDFAndQRCode.git

代码在com.http.NetworkHttps.java 中,可以直接下载demo,查看

package com.http;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
//import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import net.sf.json.JSONObject;

public class NetworkHttps {

//网络枚举
public static final String FAILURE = "failure";//失败
public static final String SUCCESSFUL = "successful"; //成功
public static final String HTTPSFAILURE = "HTTPSFAILURE"; //网络失败
public static final String HTTPSSUCCESSFUL = "HTTPSSUCCESSFUL"; //网络成功
public static final String IOERROR = "IOERROR"; //流错误
public static final String IOSUCCESSFUL = "IORSUCCESSFUL"; //流成功
public static final String PARSINGJSONSUCCESSFUL = "PARSINGJSONSUCCESSFUL";//解析数据成功
public static final String PARSINGJSONFAILURE = "PARSINGJSONFAILURE";//解析识别失败
// 对比状态
public enum ContrastState { FAILURE, SUCCESSFUL, HTTPSFAILURE, HTTPSSUCCESSFUL, IOERROR, IORSUCCESSFUL,PARSINGJSONSUCCESSFUL,PARSINGJSONFAILURE  }

//key
private static final String APIKEY = "USU89rsQjz-sy2If5Mvw-KLHyUtLqKTP";
private static final String APISECRET = "rpAXY_MmNU5ja7gjm1vUCNtMlwAAihPr";

/**
*
* @param key               --- 请求的 key
* @param secret            -- 请求的secrt
* @param imagePath         -- 第一张头像的照片
* @param imagePath2        -- 第二张头像的照片
* @param httpPath          -- 请求路径
* @return map("state"="状态", "json" = "返回 json 数据")
* @throws ClientProtocolException
* @throws IOException
*/
public static Map<String, Object> postFrameDate(String key,String secret,String imagePath,String imagePath2,String httpPath) {

Map<String, Object> map = new HashMap<String, Object>();
JSONObject json = null;

MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,"----------ThIs_Is_tHe_bouNdaRY_$", Charset.defaultCharset());
try {
multipartEntity.addPart("apikey",new StringBody(key, Charset.forName("UTF-8")));
multipartEntity.addPart("apisecret",new StringBody(secret,Charset.forName("UTF-8")));
multipartEntity.addPart("aaa", new StringBody(secret,Charset.forName("UTF-8")));
//判断是不是,人脸对比(2张图片),人脸识别(1张图片)
if (imagePath2 != null && !"".equals(imagePath2)) {

multipartEntity.addPart("image_file1", new FileBody(new File(imagePath),"image/png"));
//(ContentBody)
multipartEntity.addPart("image_file2", new FileBody(new File(imagePath2),"image/png"));
}
else {
multipartEntity.addPart("image_file", new FileBody(new File(imagePath),"image/png"));
//multipartEntity.addPart("return_landmark",new StringBody("1", Charset.forName("UTF-8")));
}

HttpPost request = new HttpPost(httpPath);
request.setEntity(multipartEntity);

request.addHeader("Content-Type","multipart/form-data; boundary=----------ThIs_Is_tHe_bouNdaRY_$");

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response =httpClient.execute(request);

InputStream is = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null) {
buffer.append(line);
}

String data = buffer.toString();
json = JSONObject.fromObject(data);
map.put("state", ContrastState.HTTPSSUCCESSFUL);
map.put("json", json);
return map;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("错误"+ e);
map.put("state", ContrastState.HTTPSFAILURE);
map.put("json",json);
return map;
}
}

/**
* 解析数据(json 数据)
* @param json
* @return map (state = "解析状态",confidence = "相似度")
*/
public Map<String, Object>  parsingJson(JSONObject json){

Map<String, Object> map = new HashMap<String, Object>();
ContrastState state ;//状态
double confidence = 0.0;//相似度

if(json != null && json.get("confidence") != null){

String string_json = json.get("confidence").toString();
confidence = Double.parseDouble(string_json);
state = ContrastState.PARSINGJSONSUCCESSFUL;
map.put("state", state);
map.put("confidence", confidence);
return map;
}

map.put("state", ContrastState.PARSINGJSONFAILURE);
map.put("confidence", confidence);
return map;
}

/************* 表单提交   最普通的方法 *****************/
// 每个post参数之间的分隔。随意设定,只要不会和其他的字符串重复即可。
private static final String BOUNDARY = "----------HV2ymHFg03ehbqgZCaKO6jyH";

/**
* 普通的方法,表单数据提交
* @param serverUrl  路径
* @param generalFormFields  提交文本数据,数组<FormFieldKeyValuePair>
* @param filesToBeUploaded  提交文件  ,数组<UploadFileItem>
* @return  ArrayList<FormFieldKeyValuePair> generalFormFields
* @throws Exception
*/
public  String sendHttpPostRequest(String serverUrl,ArrayList<FormFieldKeyValuePair> generalFormFields, ArrayList<UploadFileItem> filesToBeUploaded) throws Exception {

// 向服务器发送post请求

URL url = new URL(serverUrl);

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// 发送POST请求必须设置如下两行

connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY);

// 头

String boundary = BOUNDARY;

// 传输内容

StringBuffer contentBody = new StringBuffer("--" + BOUNDARY);

// 尾

String endBoundary = "\r\n--" + boundary + "--\r\n";

OutputStream out = connection.getOutputStream();

// 1. 处理文字形式的POST请求

for (FormFieldKeyValuePair ffkvp : generalFormFields)  {

contentBody.append("\r\n")

.append("Content-Disposition: form-data; name=\"")

.append(ffkvp.getKey() + "\"")

.append("\r\n")

.append("\r\n")

.append(ffkvp.getValue())

.append("\r\n")

.append("--")

.append(boundary);

}

String boundaryMessage1 = contentBody.toString();

out.write(boundaryMessage1.getBytes("utf-8"));

// 2. 处理文件上传

for (UploadFileItem ufi : filesToBeUploaded)

{

contentBody = new StringBuffer();

contentBody.append("\r\n")

.append("Content-Disposition:form-data; name=\"")

.append(ufi.getFormFieldName() + "\"; ") // form中field的名称

.append("filename=\"")

.append(ufi.getFileName() + "\"") // 上传文件的文件名,包括目录

.append("\r\n")

.append("Content-Type:application/octet-stream")

.append("\r\n\r\n");

String boundaryMessage2 = contentBody.toString();

out.write(boundaryMessage2.getBytes("utf-8"));

// 开始真正向服务器写文件

File file = new File(ufi.getFileName());

DataInputStream dis = new DataInputStream(new FileInputStream(file));

int bytes = 0;

byte[] bufferOut = new byte[(int) file.length()];

bytes = dis.read(bufferOut);

out.write(bufferOut, 0, bytes);

dis.close();

contentBody.append("------------HV2ymHFg03ehbqgZCaKO6jyH");

String boundaryMessage = contentBody.toString();

out.write(boundaryMessage.getBytes("utf-8"));

// System.out.println(boundaryMessage);

}

out.write("------------HV2ymHFg03ehbqgZCaKO6jyH--\r\n"
.getBytes("UTF-8"));

// 3. 写结尾

out.write(endBoundary.getBytes("utf-8"));

out.flush();

out.close();

// 4. 从服务器获得回答的内容

String strLine = "";

String strResponse = "";

InputStream in = connection.getInputStream();

BufferedReader reader = new BufferedReader(new InputStreamReader(in));

while ((strLine = reader.readLine()) != null)

{

strResponse += strLine + "\n";

}

// System.out.print(strResponse);

return strResponse;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 表单 数据