主要通过修改post输入输出流
package com.hodehtml.basic;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class RestUtil {
private static final Log logger = LogFactory.getLog(RestUtil.class);
/**
* post请求
*/
public static String sendPost(String restUrl, String param) {
String result = "";
int responseCode;
HttpURLConnection conn = null;
try {
// 打开URL
StringBuilder sbURL = new StringBuilder(restUrl);
URL url = new URL(sbURL.toString());
conn = (HttpURLConnection) url.openConnection();
// conn.setRequestMethod(“POST”);
// conn.setRequestProperty(“Content-Type”, “application/json;charset=utf-8”);
// 请求体参数设置
//System.out.println(“request param:” + param);
// 加入请求体
conn.setRequestProperty(“accept”, “/”);
conn.setRequestProperty(“connection”, “Keep-Alive”);
conn.setRequestProperty(“user-agent”,
“Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)”);
conn.setConnectTimeout(30 * 1000);
conn.setReadTimeout(180 * 1000);
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
//输入流
//OutputStream os = conn.getOutputStream();
OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
os.write(param);
os.flush();
// 输出response code
responseCode = conn.getResponseCode();
// 输出response
if(responseCode == 200){
//输出流
//BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
result = reader.readLine();
}else{
result="false";
}
// 断开连接
conn.disconnect();
} catch (Exception e) {
result="false";
conn.disconnect();
logger.error("post请求提交失败:" + restUrl, e);
}
return result;
}
}