对于请求头Content-Type,默认application/x-www-form-urlencoded。java
一、(可用)缓存
CloseableHttpClient client = HttpClients.createDefault();
// 实例化一个post对象
HttpPost post = new HttpPost(“url”);
// 使用NameValuePair将发送的参数打包
List<NameValuePair> list = new ArrayList<NameValuePair>();
// 打包传参
list.add(new BasicNameValuePair("xmlContent", requestXml));
// 使用URLEncodedFormEntity工具类实现一个entity对象,并使用NameValuePair中的数据进行初始化
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list, Consts.UTF_8);
// 将实例化的 entity对象放到post对象的请求体中
post.setEntity(formEntity);
// 创建一个响应对象, 接受客户端执行post后的响应结果
CloseableHttpResponse response = client.execute(post);
// 从实体中提取结果数据
String result = EntityUtils.toString(response.getEntity(),"UTF-8");app
二、(可用)工具
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(HQCInterConstant.GATE_URL);
HttpResponse resp = null;
// 使用NameValuePair将发送的参数打包
List<NameValuePair> list = new ArrayList<NameValuePair>();
// 打包
list.add(new BasicNameValuePair("xmlContent", requestXml));
// 使用URLEncodedFormEntity工具类实现一个entity对象,并使用NameValuePair中的数据进行初始化
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list, Consts.UTF_8);
// 将实例化的 entity对象放到post对象的请求体中
post.setEntity(formEntity);
resp = client.execute(post);
if (resp.getStatusLine().getStatusCode() == 200) {
System.out.println("ok");
}
String result= EntityUtils.toString(resp.getEntity(),"UTF-8"); post
三、(可用)url
// URL url = new URL(HQCInterConstant.GATE_URL);
// HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.setConnectTimeout(30000); // 设置链接主机超时(单位:毫秒)
// conn.setReadTimeout(30000); // 设置从主机读取数据超时(单位:毫秒)
// conn.setDoOutput(true); // post请求参数要放在http正文内,顾设置成true,默认是false
// conn.setDoInput(true); // 设置是否从httpUrlConnection读入,默认状况下是true
// conn.setUseCaches(false); // Post 请求不能使用缓存
// // 设定传送的内容类型是可序列化的java对象(若是不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
// conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// conn.setRequestMethod("POST");// 设定请求的方法为"POST",默认是GET
// //conn.setRequestProperty("Content-Length", requestXml.length() + "");
// requestXml="xmlContent="+URLEncoder.encode(requestXml, "UTF-8");
// OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
// out.write(requestXml.toString());
// out.flush();
// out.close();
// if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
// return null;
// }
// // 获取响应内容体
// BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
// String line = null;
// StringBuffer strBuf = new StringBuffer();
// while ((line = in.readLine()) != null) {
// strBuf.append(line).append("\n");
// }
// in.close();code