java发送post请求以raw形式和 Params形式发送2.0(RestTemplate)
在对接第三方平台时遇到了好几个坑,,发送raw形式的请求时一直返回参数不存在搞得我欲不痛生,,,,
之后用postman测试了一下,发现用postman的raw形式的请求不行
换成postman的Params形式的请求就可以
所以提供了两种发送给大家参考
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.Map.Entry;
/**
* header 在传输header时请务必加上charset=utf-8;
* "Content-Type: application/x-www-form-urlencoded;charset=utf-8\n"
*/
public static final String HEADER =
"Accept-Encoding: gzip,deflate\n" +
"Content-Type: application/x-www-form-urlencoded;charset=utf-8\n" +
"Connection: Keep-Alive";
/**
* @param url 访问地址
* @param param 需要传输参数参数;对象可以通过json转换成String
* @param header header 参数;可以通过下面工具类将string类型转换成map
* @return 返回网页返回的数据
*/
public static String sendPost(String url, String param, Map<String, String> header) throws UnsupportedEncodingException, IOException {
OutputStreamWriter out;
BufferedReader in = null;
String result = "";
URL realUrl = new URL(url);
// 打开和URL之间的连接
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
//设置超时时间
conn.setConnectTimeout(5000);
conn.setReadTimeout(15000);
// 设置通用的请求属性
if (header!=null) {
for (Entry<String, String> entry : header.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
conn.setRequestMethod("POST");
conn.addRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new OutputStreamWriter( conn.getOutputStream(),"UTF-8");// utf-8编码
// 发送请求参数
out.write(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
return result;
}
/**
* @param url 访问地址
* @param headerMap header 参数;可以通过下面工具类将string类型转换成map
* @param contentMap 需要传输参数参数;对象可以通过json转换成map
* @return 返回网页返回的数据
*/
public static String postMap(String url, Map<String, String> headerMap, Map<String, String> contentMap) {
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
List<NameValuePair> content = new ArrayList<NameValuePair>();
//将content生成entity
Iterator iterator = contentMap.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, String> elem = (Entry<String, String>) iterator.next();
content.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
}
CloseableHttpResponse response = null;
try {
//循环增加header
Iterator headerIterator = headerMap.entrySet().iterator();
while (headerIterator.hasNext()) {
Entry<String, String> elem = (Entry<String, String>) headerIterator.next();
post.addHeader(elem.getKey(), elem.getValue());
}
if (content.size() > 0) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(content, "UTF-8");
post.setEntity(entity);
}
//发送请求并接收返回数据
response = httpClient.execute(post);
if (response != null && response.getStatusLine().getStatusCode() == 200) {
//获取response的body部分
HttpEntity entity = response.getEntity();
//读取reponse的body部分并转化成字符串
result = EntityUtils.toString(entity);
}
return result;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
*Header字符串转map
* @param zz
* @return
*/
public static Map<String, String> splid(String zz) {
String[] stepOne = zz.split("\n");
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i < stepOne.length; i++) {
String[] stepTwo = stepOne[i].split(": ");
if (map.get(stepTwo[0]) == null) {
map.put(stepTwo[0], stepTwo[1]);
} else {
map.put(stepTwo[0], stepTwo[1] + "," + map.get(stepTwo[0]));
}
}
return map;
}