使用HttpURLConnection发送post和get请求

但我们常常会碰到这样一种情况:

通过HttpURLConnection来模拟模拟用户登录Web服务器,服务器使用cookie进行用户认证。在模拟登录时,Post表单数据后可以正确登录(登陆成功时会response一个cookie,然后redirect到main page,不成功则redirect到login page),但是在使用HttpURLConnection再次连接服务器其他页面(或者即使是当前的response里是redirect的page)时,服务器都会认为是全新的一个Session。

解决方法有2步:

1. 调用HttpURLConnection (send post request to login page)的setInstanceFollowRedirects()方法,参数为false (这样不会去获取redirect page)

2. 获取HttpURLConnection send post request to login page的session id,然后在之后每一次的connection里都加上该session id

    public static String sessionId = "";
public static void sendLoginRequest() throws IOException {
URL loginUrl = new URL("http://xxx");
HttpURLConnection connection = (HttpURLConnection) loginUrl.openConnection(); // Output to the connection. Default is
// false, set to true because post
// method must write something to the
// connection
// 设置是否向connection输出,因为这个是post请求,参数要放在
// http正文内,因此需要设为true
connection.setDoOutput(true);
// Read from the connection. Default is true.
connection.setDoInput(true);
// Set the post method. Default is GET
connection.setRequestMethod("POST");
// Post cannot use caches
// Post 请求不能使用缓存
connection.setUseCaches(false); // This method takes effects to
// every instances of this class.
// URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。
// connection.setFollowRedirects(true); // This methods only
// takes effacts to this
// instance.
// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
connection.setInstanceFollowRedirects(false); // Set the content type to urlencoded,
// because we will write
// some URL-encoded content to the
// connection. Settings above must be set before connect!
// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
// 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode
// 进行编码
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
// 要注意的是connection.getOutputStream会隐含的进行connect。
connection.connect(); DataOutputStream out = new DataOutputStream(connection
.getOutputStream()); // 要传的参数
String content = URLEncoder.encode("username", "UTF-8") + "="
+ URLEncoder.encode("XXX", "UTF-8");
content += "&" + URLEncoder.encode("password", "UTF-8") + "="
+ URLEncoder.encode("XXXX", "UTF-8"); // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
out.writeBytes(content); out.flush();
out.close(); // flush and close //Get Session ID
String key = "";
if (connection != null) {
for (int i = 1; (key = connection.getHeaderFieldKey(i)) != null; i++) {
if (key.equalsIgnoreCase("set-cookie")) {
sessionId = connection.getHeaderField(key);
sessionId = sessionId.substring(0, sessionId.indexOf(";"));
}
}
}
connection.disconnect();
}

然后之后每一次connection都要加上这个session id:

URL url = new URL("http:......");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("Cookie",this.sessionId);
connection.connect();

Http学习之使用HttpURLConnection发送post和get请求(3)的更多相关文章

  1. Http学习之使用HttpURLConnection发送post和get请求(2)

    接上节Http学习之使用HttpURLConnection发送post和get请求 本节深入学习post请求. 上 节说道,post请求的OutputStream实际上不是网络流,而是写入内存,在ge ...

  2. Http学习之使用HttpURLConnection发送post和get请求(1)

    最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,post与get的不同之处在于post的参数不是放在URL字串里面,而是放 ...

  3. HttpURLConnection发送GET、POST请求

    HttpURLConnection发送GET.POST请求 /** * GET请求 * * @param requestUrl 请求地址 * @return */ public String get( ...

  4. 谈谈Java利用原始HttpURLConnection发送POST数据

    这篇文章主要给大家介绍java利用原始httpUrlConnection发送post数据,设计到httpUrlConnection类的相关知识,感兴趣的朋友跟着小编一起学习吧 URLConnectio ...

  5. HttpUrlConnection发送url请求(后台springmvc)

    1.HttpURLConnection发送url请求 public class JavaRequest { private static final String BASE_URL = "h ...

  6. HTTPURLConnection 发送Post数据

    在使用HTTPURLConnection发送POST数据时,通常使用如下方式: byte[] body = new byte[512]; // 需要发送的body数据 URL url = new UR ...

  7. HttpURLConnection发送POST请求(可包含文件)

    import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io. ...

  8. JAVA使用原始HttpURLConnection发送POST数据

    package com.newflypig.demo; /** * 使用jdk自带的HttpURLConnection向URL发送POST请求并输出响应结果 * 参数使用流传递,并且硬编码为字符串&q ...

  9. HttpURLConnection发送请求

    每个 HttpURLConnection 实例都可用于生成单个请求,但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络.请求后在 HttpURLConnection 的 InputStrea ...

随机推荐

  1. [转]centos7环境安装rabbitMQ

    使用专业的消息队列产品rabbitmq之centos7环境安装 http://www.cnblogs.com/huangxincheng/p/6006569.html CentOS7上安装Rabbit ...

  2. [认证授权] 3.基于OAuth2的认证(译)

    OAuth 2.0 规范定义了一个授权(delegation)协议,对于使用Web的应用程序和API在网络上传递授权决策非常有用.OAuth被用在各钟各样的应用程序中,包括提供用户认证的机制.这导致许 ...

  3. jQuery插件制作

    模板:(function($){ $.fn.plugins=function(options){ var defaults = { } var options = $.extend(defaults, ...

  4. IOS——触摸事件 视图检测和事件传递

    iPhone上有非常流畅的用户触摸交互体验,能检测各种手势:点击,滑动,放大缩小,旋转.大多数情况都是用UI*GestureRecognizer这样的手势对象来关联手势事件和手势处理函数.也有时候,会 ...

  5. libev事件库使用笔记

    源码下载地址:http://dist.schmorp.de/libev/ libev是一个高性能的事件循环库,比libevent库的性能要好. 安装: tar -zxf libev-4.15.tar. ...

  6. 自己实现的string的库函数

    为了更好地理解string的各个库函数,现将几个常用的库函数用自己的方式实现如下: #include<iostream> using namespace std; #include< ...

  7. 从网络通信角度谈web性能优化

    衡量一个网站的性能有多个指标,DNS解析时间,TCP链接时间,HTTP重定向时间,等待服务器响应时间等等,从用户角度来看,就可以归结为该网站访问速度的快慢.也就是说性能等于网站的访问速度. 早些年Am ...

  8. SELECT中(非常)常用的子查询操作

    MySQL中的子查询 是在MySQL中经常使用到的一个操作,不仅仅是用在DQL语句中,在DDL语句.DML语句中也都会常用到子查询. 子查询的定义: 子查询是将一个查询语句嵌套在另一个查询语句中: 在 ...

  9. [ext4]05 磁盘布局 - 延迟块组初始化

    延迟块组初始化,Ext4的新特性.如果对应的特性标识uninit_bg置位,那么inode bitmap和inode tables就不会初始化. 延迟块组初始化特性特性可以减少格式化耗时. 延迟块组初 ...

  10. java.net.SocketException: Broken pipe 异常可能的原因

    org.apache.catalina.connector.ClientAbortException: java.net.SocketException: Broken pipe at org.apa ...