使用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. bootstrap(响应式)加减输入框

    <div class="row">  <div class="col-lg-6">    <div class="inp ...

  2. js随机模块颜色

    <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content ...

  3. Hibernate基础学习(七)—检索方式

    一.概述      Hibernate有五种检索方式. 1.导航对象图检索方式      根据已经加载的对象,导航到其他对象. Order order = (Order)session.get(Ord ...

  4. MyEclipse常见错误

    1.Could not create the view: An unexpected exception was thrown java.lang.NullPointerException     a ...

  5. 一、iOS中的事件可以分为3大类型

    触摸事件加速计事件远程控制事件 响应者对象在iOS中不是任何对象都能处理事件,只有继承了UIResponder的对象才能接收并处理事件.我们称之为"响应者对象" UIApplica ...

  6. JS模式---命令模式

    var opendoor = { execute: function () { console.log("开门"); } }; var closedoor = { execute: ...

  7. tomcat的常用配置

    1.解決get请求的中文乱码问题 解决办法: 首先找到tomcat路径下的apache-tomcat-7.0.52\conf文件夹,打开server.xml文件,编辑如下内容: <Connect ...

  8. js事件相关面试题

    说是面试题,其实也相当于是对js事件部分知识点的一个总结.简单内容一笔带过,了解详情我都给出了参考链接,都是之前写的一些相关文章.JavaScript本身没有事件模型,但是环境可以有. DOM:add ...

  9. Python:学会创建并调用函数

    这是关于Python的第4篇文章,主要介绍下如何创建并调用函数. print():是打印放入对象的函数 len():是返回对象长度的函数 input():是让用户输入对象的函数 ... 简单来说,函数 ...

  10. input 显示/隐藏密码

    js代码: // 显示/隐藏密码 $('.open').on('click',function(){ if($("#psw").prop('type')=='password'){ ...