package common;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import ewebeditor.admin.main_jsp;
import net.sf.json.JSONArray;
public class Test {
public void requestByPostMethod() {
CloseableHttpClient httpClient = getHttpClient();
try {
HttpPost post = new HttpPost("http://59.195.128.222:88/accept/service/SubmitResult");
// 创建参数列表
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(new BasicNameValuePair("ID", "1408528201809100028"));
list.add(new BasicNameValuePair("Result", "1"));
list.add(new BasicNameValuePair("Opinion", "通過"));
list.add(new BasicNameValuePair("LicenceCode", ""));
list.add(new BasicNameValuePair("LicenceName", ""));
list.add(new BasicNameValuePair("SystemCode", "B59B876284C441A5BAFD944A86F7648D"));
String name = "方子君";
String time = "2018-09-17 17:09:00";
Base64 base64 = new Base64();
try {
list.add(new BasicNameValuePair("DeliverUser",
base64.encodeToString(name.getBytes("UTF-8")).replaceAll("[\\s*\t\n\r]", "")));
list.add(new BasicNameValuePair("DeliverTime",
base64.encodeToString(time.getBytes("UTF-8")).replaceAll("[\\s*\t\n\r]", "")));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
List list1 = new ArrayList();
JSONArray json = JSONArray.fromObject(list1);
list.add(new BasicNameValuePair("fileJson", json.toString()));
// url格式编码
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list, "UTF-8");
post.setEntity(uefEntity);
HttpEntity entity2 = post.getEntity();
System.out.println("=====================" + EntityUtils.toString(entity2, "utf-8")); // 获取网页内容
System.out.println("POST 请求...." + post.getURI());
// 执行请求
CloseableHttpResponse httpResponse = httpClient.execute(post);
try {
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
System.out.println("result:" + result);
} finally {
httpResponse.close();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
closeHttpClient(httpClient);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private CloseableHttpClient getHttpClient() {
return HttpClients.createDefault();
}
private void closeHttpClient(CloseableHttpClient client) throws IOException {
if (client != null) {
client.close();
}
}
public static void main(String[] args) {
Test t = new Test();
t.requestByPostMethod();
}
}