使用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. maven私服搭建nexus介绍(二)

    1.各个仓库介绍 Hosted:宿主仓库 主要放本公司开发的SNAPSHOTS测试版本,RELEASES正式发行版.合作公司第三方的jar包. Proxy:代理仓库 代理中央仓库:代理Apache下测 ...

  2. ios 检测屏幕方向

    方法一:通知中心监听 name: // UIDeviceOrientationDidChangeNotification   允许方向改变的情况下,监听设备方向,与电池条无关 // UIApplica ...

  3. CSAcademy Beta Round #5 Long Journey

    题目链接:https://csacademy.com/contest/arhiva/#task/long_journey/ 大意是有一张无向不带权的图,两个人同时从s点出发,分别前往a点和b点,且每个 ...

  4. C语言之函数和字符串

    二.函数: 2.1.函数的执行: 1.当我们每次进入一个函数的时候,原函数的栈底进行一个备份,之后将当前函数的栈底和栈顶指针分作同一个. 2.此时我们就可以说产生了一个新栈,产生新栈之后会在新栈中申请 ...

  5. stl_组件

    2.1.STL中: 2.1.1.包含常用的数据结构. 2.1.2.包含常用的基本算法.结构和算法其实就是一些接口. 2.1.3.提供了一套可扩展的框架. 2.2.六大组件: 2.2.1.容器组件(基本 ...

  6. Swift、Objective-C 单例模式 (Singleton)

    Swift.Objective-C 单例模式 (Singleton) 本文的单例模式分为严格单例模式和不严格单例模式.单例模式要求一个类有一个实例,有公开接口可以访问这个实例.严格单例模式,要求一个类 ...

  7. Spring Boot快速建立HelloWorld项目

    Spring Boot使我们更容易去创建基于Spring的独立和产品级的可以”即时运行“的应用和服务.支持约定大于配置,目的是尽可能快地构建和运行Spring应用. 构建环境 JDK 6+ Maven ...

  8. 关于WebGIS开源解决方案的探讨(转载)

    1.背景 公司目前的多数项目采用的是ArcGIS产品+Oracle+WebLogic/Tomcat/APUSIC/WebShpere这样的架构.由于 公司从事的是政府项目,甲方单位普遍均采购有以上产品 ...

  9. 1014 Uniform Generator

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submission( ...

  10. 【Objective-C 基础】3.类

     1.类 OC中类分为两个文件: .h类的声明文件,用于声明变量.函数. .m类的实现文件,用于实现.h中的函数 类的声明使用关键字@interface @end 类的实现使用关键字@implemen ...