使用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. 【Android】XML文件的解析

    1.首先我们可以在res包路径下创建一个raw包,然后在raw下创建一个email.xml 文件,并修改其内容如下: <?xml version="1.0" encoding ...

  2. Oracle wm_concat()函数

    oracle wm_concat(column)函数使我们经常会使用到的,下面就教您如何使用oraclewm_concat(column)函数实现字段合并 如: shopping:   ------- ...

  3. Doxygen + Graphviz windows下安装配置(图解)

    查看一些开源代码经常被一些函数的调用关系给绕进去,经过网上查阅资料,发现了这个好用的方法,拿出来和大家分享下安装和应用的过程. 本人常用windows系统,所以主要讲解下windows下相关的内容 要 ...

  4. php最新微信扫码在线支付接口。ecshop和shopex,shopnc下完美无错

    最近为客户的一个在线商城做了一个微信扫码在线支付的接口.跟大家分享一下. 1 首先可以模仿其他的接口,比如支付宝,财付通等的接口,构建模块功能文件和语言文件.2 微信提供2种扫码方式,大家可以根据自己 ...

  5. nginx学习笔记——http module分析

         源码:nginx 1.12.0           nginx由于其高性能.扩充性好等特点在迅速走红,越来越多的公司采用nginx作web服务器.负载均衡.waf等 工作,一些基于nginx ...

  6. 安装hadoop2.7.3

    hadoop3与hadoop2.x的变化很大,hadoop3很多东西现在做起来太麻烦了,这里先安装hadoop2.7.3 此贴学习地址http://www.yiibai.com/t/mapreduce ...

  7. 【stm32】时钟树解析

    有时候会突然忘了这个重要的时钟树,这里转载一个比较好的,以防忘记. STM32时钟系统 在STM32中,有五个时钟源,为HSI.HSE.LSI.LSE.PLL. ①HSI是高速内部时钟,RC振荡器,频 ...

  8. 浅析c++/java/c#三大热门编程语言的运行效率

    从安全角度考虑,C#是这几中语言中最为安全的,它其中定义的相关安全机制很好的确保了系统的安全... 今天和同学们一起探讨下c++/java/c# 三大热门语言的运行效率情况,以及各自的用途. 估计有很 ...

  9. Atom手动安装插件和模块的解决方案

    最近开始使用Atom编辑器写作.为了预览带LaTeX公式的markdown文档,尝试安装插件markdown-preview-plus,但是总是失败.经过仔细查看错误输出和网上相关问答,发现尽管报错为 ...

  10. 各种 SVG 制作单选和多选框动画

    在线演示      源码下载