有时候真的挺反感的。到处都是装
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONObject;
public class HttpRequestUtil {
private static Logger logger = Logger.getLogger(HttpRequestUtil.class);
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String post(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
System.out.println("**************开始发送post请求*****************");
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "application/json");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "application/json");
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 PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
/**
* 向指定URL 发送get请求
* @param urlStr
* 要访问的URL
* @param param
* @return
* @throws Exception
*/
public static String get(String urlStr ,String param) throws Exception{
urlStr=urlStr+"?"+param;
URL url = new URL(urlStr);
URLConnection connection = url.openConnection();
/**
* 然后把连接设为输出模式。URLConnection通常作为输入来使用,比如下载一个Web页。
* 通过把URLConnection设为输出,你可以把数据向你个Web页传送。下面是如何做:
*/
connection.setDoOutput(true);
/**
* 最后,为了得到OutputStream,简单起见,把它约束在Writer并且放入POST信息中,例如: ...
*/
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream(), "utf-8");
// remember to clean up
out.flush();
out.close();
/**
* 这样就可以发送一个看起来象这样的POST: POST /jobsearch/jobsearch.cgi HTTP 1.0 ACCEPT:
* text/plain Content-type: application/x-www-form-urlencoded
* Content-length: 99 username=bob password=someword
*/
// 一旦发送成功,用以下方法就可以得到服务器的回应:
String sCurrentLine;
String sTotalString;
sCurrentLine = "";
sTotalString = "";
InputStream l_urlStream;
l_urlStream = connection.getInputStream();
// 传说中的三层包装阿!
BufferedReader l_reader = new BufferedReader(new InputStreamReader(
l_urlStream,"utf-8"));
while ((sCurrentLine = l_reader.readLine()) != null) {
sTotalString += sCurrentLine;
}
logger.info("###########################################");
return sTotalString;
}
public static String getRequsetData(HttpServletRequest request) throws IOException{
BufferedReader reader = null;
StringBuilder result = new StringBuilder();
try {
request.setCharacterEncoding("UTF-8");
// post方式传递读取字符流
reader = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
String jsonStr = null;
while ((jsonStr = reader.readLine()) != null) {
result.append(jsonStr);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result.toString();
}
public static String getRequestPostStr(HttpServletRequest request)
throws IOException {
byte buffer[] = getRequestPostBytes(request);
String charEncoding = request.getCharacterEncoding();
if (charEncoding == null) {
charEncoding = "UTF-8";
}
return new String(buffer, charEncoding);
}
public static byte[] getRequestPostBytes(HttpServletRequest request)
throws IOException {
int contentLength = request.getContentLength();
if(contentLength<0){
return null;
}
byte buffer[] = new byte[contentLength];
for (int i = 0; i < contentLength;) {
int readlen = request.getInputStream().read(buffer, i,
contentLength - i);
if (readlen == -1) {
break;
}
i += readlen;
}
return buffer;
}
}
/**
* post方式接收数据
* @param request
* @param response
* @return
*/
@RequestMapping(value="receivepost", method=RequestMethod.POST, produces="application/json;UTF-8")
@ResponseBody
public Object receivepost(HttpServletRequest request, HttpServletResponse response){
System.out.println("******** 接收POST方式开始 **************");
JSONObject json = new JSONObject();
String data;
try {
data = getRequsetData(request);
System.out.println("数据data:" + data);
JSONObject jsStr = JSONObject.parseObject(data);
String a = jsStr.getString("a"); // 数据
//Do Whatever you want
......
public static String getRequsetData(HttpServletRequest request) throws IOException{
BufferedReader reader = null;
StringBuilder result = new StringBuilder();
try {
request.setCharacterEncoding("UTF-8");
// post方式传递读取字符流
reader = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
String jsonStr = null;
while ((jsonStr = reader.readLine()) != null) {
result.append(jsonStr);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result.toString();
}