- 浏览: 60797 次
- 性别:
- 来自: 四川
最新评论
通常情况下,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
发表评论
-
struts2 中获取 web资源的方式
2016-01-08 17:02 487在struts2中获取 web资源的方式大致可分为获取扩展 ... -
sql server、db2、oracle 存储过程动态sql语句示例
2015-01-31 19:00 1800Oracle CREATE OR REPLACE PRO ... -
ie9 中出现不明的异常(参数是必选项 (Argument not optional)、尚未实现)等
2015-01-27 23:57 1279<script type="text/jav ... -
SAXParseException: The content of element type "configuration" must match
2014-09-15 23:57 1934在mybatis的配置文件中新增加<databaseI ... -
java.lang.ClassNotFoundException: Cannot find class: DB_VENDOR
2014-09-15 23:45 1943在mybatis 中使用databaseIdProvide ... -
spring mvc3 + fastjson 转换 REST 参数以及输出
2014-03-27 00:16 4205spring 3可以支持Rest风格参数,其内置了jack ... -
eclipse中编辑log4j 的xml配置文件时,自动提示
2014-03-27 00:05 855方法1. 配置log4j.dtd文件: Windows - ... -
java json 转换之 Jackson 框架
2013-08-01 21:50 1123转自:http://www.cnblogs.com/hooj ... -
eclipse/myeclise 自定义注释中的变量名称
2013-07-01 23:18 950eclipse/myeclipse中自带了 ... -
Eclipse Class Decompiler——Java反编译插件
2012-11-08 22:41 1213Eclipse Class Decompiler,整 ... -
struts+spring+hibernate整合问题解决方法 陆续更新中....
2009-01-01 10:33 852在整合ssh过程中出现的问题和解决方法: 一、 严重: Ser ... -
DWR通过Annotation与spring整合
2009-01-21 22:05 640DWR 2.0 增加了一个很有趣的新特性,Annotat ... -
div嵌套页面 div加载页面 (其中获取目标页面的内容是用dwr框架连接java程序做的)
2009-03-15 16:58 639前段时间因为有需要,要在div中加载一个页面。但是以前没做过, ... -
tapestry autocomplete 更改样式及定位
2009-07-09 19:02 692版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文 ... -
Java中的main()方法详解
2009-07-12 16:23 619源文作者:leizhimin 源文链接:http:/ ... -
tapestry5 集成 spring 的事务管理
2009-07-22 15:43 566说明:使用的是tapestry5.1.0.5 和spring ... -
tapestry5 布局 参数的处理
2009-07-23 17:24 386<?xml version="1.0" ... -
tapestry不支持 等html特殊符号的解决方法
2009-07-23 17:34 492在使用tapestry时,偶然发现使用 &a ... -
WebService大讲堂之Axis2(1):用POJO实现0配置的WebService
2009-07-28 15:01 407转自:http://space.itpub.net ... -
WebService大讲堂之Axis2(2):复合类型数据的传递
2009-07-28 15:25 479转自:http://space.itpub.net/12921 ...
相关推荐
使用HttpUrlConnection实现上传文件服务器端代码,引用commons-fileupload-1.2.1.jar、commons-io-1.4.jar
本例演示最简单的android客户端和服务器端通信,客户端使用android4.0以上版本,服务器端为dynamic web project工程,使用时将client代码中的ip地址改为自己电脑的ipv4地址,同时保证手机和电脑处于同一网络下(内网...
java网络请求工具类 HttpURLConnection post请求工具类HttpURLConnection httpURLConnection = (HttpURLConnection) url .openConnection(); httpURLConnection.setRequestMethod("POST");// 提交模式
java实现多次HttpURLConnection共享session,发送两次请求共享同一个session,这样做爬虫的时候就可以爬网站登录后能看到的内容了
基于HttpURLConnection的封装http请求,进行了https校验忽略,对get和post进行了整合,更方便请求,对header以及超时的进行了可配置化处理,对返回也进行了封装,便于请求结果的处理。
这个是我自己集成框架的时候写的一个HTTP请求的辅助类,主要是通过HttpURLConnection 来实现JAVA的HTTP请求,有的人会问、为什么有些网站发请求没问题,有些网站发请求却返回数据,在给网站发送请求的时候,请看清楚...
HttpURLConnection请求和HttpClient请求...................................................................
httpurlconnection 获取服务器数据并解析
创建HTTP连接:使用Java.net包中的HttpURLConnection类来创建HTTP连接,从而可以发送POST请求并接收响应。 设置请求参数:设置请求参数,包括请求方法、请求头、请求体等信息。我们的示例代码中包括了常见的请求头...
设置HTTP请求使用的方法:conn.setRequestMethod("GET"); 设置连接超时,读取超时的毫秒数,以及服务器希望得到的一些消息头 conn.setConnectTimeout(6*1000); 获取服务器的响应码并进行判断,正确的响应码一般为200...
Java利用HttpURLConnection发送post请求上传文件
HttpURLConnection的(get请求、post请求)
HttpUrlConnection对象模拟POST带JSON字符串的AJAX请求失败! 我的目的是抓取响应结果字符串"301",但抓取的结果是一堆HTML代码,哪位大神看看哪有毛病?
httpurlconnection, http post, http get
远程连接服务器HttpURLConnection,该工具有上传到远程服务器的方法,供参考远程连接服务器HttpURLConnection,该工具有上传到远程服务器的方法,供参考
自己写了一个基于httpurlconnection和Asynctask的例子
Android客户端向服务器端请求数据的两种主要方式:HTTPURLConnection、HTTPClient;内含客户端与服务器端Demo(带有详细注释),原生方式解析json数据,希望大家多多批评指教!!
首先客户端从服务器端获取json数据 1、利用HttpUrlConnection 代码如下:/** * 从指定的URL中获取数组 * @param urlPath * @return * @throws Exception */ public static String readParse(String urlPath) ...
HttpUrlConnection 用Post方式提交请求 ,我找的不容易,需要的时候很重要
//使用POST提交 hc.addRequestProperty("Cookie", getSessionId()); hc.setDoOutput(true); hc.connect(); OutputStream out = hc.getOutputStream(); //参数是a=""&b=""这样拼接的一个串 out....