注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

放飞自由

年轻人,如果三年的时间里,没有任何想法,他这一生,就基本这个样子,没有多大改变。

 
 
 

日志

 
 

Http学习之使用HttpURLConnection发送post和get请求  

2012-07-17 16:02:15|  分类: JAVA后台 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

package com.huawei.bjwxcs.common.proxy;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;

public class CProxyHandler extends HttpServlet {

private static final long serialVersionUID = 1L;

private final Logger logger = Logger.getLogger(getClass());

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
String log_url = "";
logger.info("------*****---------------------doGet start----------------------------------");
String primaryUrl = "";
OutputStream out = null;
HttpURLConnection conn = null;
try {
//$.ajax{ url : CFG.proxyHandler + "http://139.124.122.143/test"}
//CFG.proxyHandler = "http://127.0.0.1/test/proxyHandler?url=";
primaryUrl = request.getQueryString();
if (primaryUrl.startsWith("url=")) {
primaryUrl = primaryUrl.substring(4);
}

//url解码
log_url = URLDecoder.decode(primaryUrl, "UTF-8");
logger.info("log_url----" + log_url);

URL url = new URL(primaryUrl);
conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("GET");

conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// conn.setConnectTimeout(3000);
out = response.getOutputStream();
response.setContentType("text/plain; charset=UTF-8");

BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), HTTP.UTF_8));
BufferedWriter wd = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), HTTP.UTF_8));

String tempLine = rd.readLine();

StringBuffer scenarioSb = new StringBuffer();

while (tempLine != null) {
wd.write(tempLine);
scenarioSb.append(tempLine);
tempLine = rd.readLine();
}

wd.flush();
logger.info("请求成功地址: " + primaryUrl + "\\r\\n");
logger.info("返回结果: " + scenarioSb.toString());
} catch (Exception e) {

} finally {
try {
if (out != null) {
out.close();
}
if (conn != null) {
conn.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
logger.info("------*****---------------------doGet end----------------------------------");
}

public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {

logger.info("------*****---------------------doPost start----------------------------------");
String log_url = "";
String reStr = null;
String primaryUrl = "";
OutputStream out = null;
HttpURLConnection conn = null;
try {
// 解析客户端发送的请求
BufferedReader reader = new BufferedReader(new InputStreamReader(
req.getInputStream(), HTTP.UTF_8));
StringBuffer reSb = new StringBuffer();
String tempStr = reader.readLine();
while (tempStr != null) {
reSb.append(tempStr);
tempStr = reader.readLine();
}
// 将POST请求内容解码
// reStr = URLDecoder.decode(reSb.toString(), "UTF-8");
reStr = reSb.toString();
// 取得实际请求地址
primaryUrl = req.getQueryString();
if (primaryUrl.startsWith("url=")) {
primaryUrl = primaryUrl.substring(4);
}
// 日志入库——url解码
log_url = URLDecoder.decode(primaryUrl, "UTF-8");
logger.info("log_url----" + log_url);
// 开始转发
URL url = new URL(primaryUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 填装POST请求的数据
DataOutputStream connOut = new DataOutputStream(conn.getOutputStream());
connOut.writeBytes(reStr);
connOut.flush();
connOut.close();

// 取得当前请求的响应
out = resp.getOutputStream();
resp.setContentType("text/plain; charset=UTF-8");

// 取得转发请求后的响应数据
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), HTTP.UTF_8));
BufferedWriter wd = new BufferedWriter(new OutputStreamWriter(out,HTTP.UTF_8));

String tempLine = rd.readLine();

StringBuffer scenarioSb = new StringBuffer();

while (tempLine != null) {
wd.write(tempLine);
scenarioSb.append(tempLine);
tempLine = rd.readLine();
}

wd.flush();
logger.info("请求成功地址: " + primaryUrl + "\\r\\n");
logger.info("返回结果: " + scenarioSb.toString());
} catch (Exception e) {
logger.info("请求出错地址: " + primaryUrl + "错误内容:" + e.getMessage());
} finally {
try {
if (out != null) {
out.close();
}
if (conn != null) {
conn.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}

}
logger.info("------*****---------------------doPost end----------------------------------");
}
}



注: post 提交有个地方需要注意,

BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream(), HTTP.UTF_8));

String userId = StringUtils.isEmpty(request.getParameter("userId")) ? "":request.getParameter("userId");

这时的req.getInputStream() 必须在request.getParameter(""); 之前执行,如果先执行 getParameter() 后,getInputStream() 取不到任何值


可参考文章:

request.getParameter()获取不到数据的问题 http://well-lf.iteye.com/blog/1543807

JDK中的URLConnection参数详解 http://www.blogjava.net/supercrsky/articles/247449.html

在httpservlet中同时使用getParameter和getInputStream时注意的问题 http://blog.csdn.net/ewsl/article/details/450613


  评论这张
 
阅读(442)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017