用HttpURLConnection在服务器端发起HTTP Post请求的例子
通常情况下,http请求都是从浏览器端发起的,如提交一个表单,或点击一个链接,都会对服务器发送一个http请求。
但如果我们想在服务器发出一个http请求,如何才能做到呢,如果只是简单的http访问,java.net.URL就足够了,如:
URL url = new URL("http://www.baidu.com");
InputStream ins = url.openStream();
//通过这个InputStream对象就可拿到返回的HTML代码
但如果我们要从服务器对远程URL发出http post访问,并且要传递一些参数,甚至还要设置某些Cookie值,那就要
借助HttpURLConnection这个类了,我们可以用URL.openConnection()方法来得到这个类的对象,具体请看下例:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws Exception {
HttpURLConnection httpConn = null;
try {
StringBuffer paramData = getQueryString(request);
String urlString = "http://localhost:8080/myweb/login.do";
URL url = new URL(urlString);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
String cookieString = getCookieString(request);
if (cookieString.length() > 0) // 往远程URL传递Cookie值
httpConn.setRequestProperty("Cookie", cookieString);
OutputStream os = httpConn.getOutputStream();
os.write(paramData.toString().getBytes()); // 往远程URL传递参数
os.flush();
os.close();
int code = httpConn.getResponseCode();
if (code == 200) { // 返回成功
BufferedReader reader = new BufferedReader(
new InputStreamReader(httpConn.getInputStream(), "utf-8"));
String line;
StringBuffer buffer = new StringBuffer();
while((line = reader.readLine()) != null) {
buffer.append(line).append("/n");
}
} else { // 访问失败
//forward error page
throw new Exception("Error occur when try to visit the url:" +
url.getPath() + " using HttpURLConnection");
}
} catch (Exception ex) {
throw new Exception("Error occur execute " +
"HttpRemoteProxy.performImpl(), the caused by " + ex);
} finally {
if (httpConn != null)
httpConn.disconnect();
}
}
/*
* 得到request所有的请求参数,并连接起来
*/
private StringBuffer getQueryString(HttpServletRequest request)
throws Exception {
Enumeration paramNames = request.getParameterNames();
StringBuffer paramData = new StringBuffer();
while (paramNames.hasMoreElements()) {
String name = (String)paramNames.nextElement();
String value = request.getParameter(name);
value = URLDecoder.decode(value, "utf-8");
paramData.append(name).append("=").append(value).append("&");
}
if (paramData.length() > 0) //delete the last char '&'
paramData.deleteCharAt(paramData.length() - 1);
return paramData;
}
/*
* 得到所有的cookie,并把它们连接起来
*/
private String getCookieString(HttpServletRequest request) throws Exception {
Cookie[] cookies = request.getCookies();
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
String value = cookie.getValue();
String name = cookie.getName();
if (value != null && !value.equals(""))
buffer.append(name).append("=").append(value).append(";");
}
if (buffer.length() > 0)
buffer.deleteCharAt(buffer.length() - 1);//delete the last char ';'
return buffer.toString();
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/Linyufa/archive/2009/07/23/4373929.aspx