使用HttpClient访问http地址,有时候会报302错误。

通过上网搜索,发现问题所在,报302是因为访问的http地址在服务端做了访问重定向,需要请求重定向后的URI。

1.简单实例,http访问返回302,此时需要获取重定向地址,继续进行重定向访问,以获取最终结果:


public class TestLogin {public static void main(String args[]) {try {HttpClient client = HttpClients.createDefault();login(client);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static void login(HttpClient client) throws Exception {final String APPLICATION_JSON = "application/json";final String CONTENT_TYPE_TEXT_JSON = "text/json";String url = "http://172.16.30.208:8092/svc/login";String js = "{\"username\":\"13800000002\",\"password\":\"123456\"}";HttpPost httpPost = new HttpPost(url);httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");StringEntity se = new StringEntity(js);se.setContentType(CONTENT_TYPE_TEXT_JSON);httpPost.setEntity(se);HttpResponse response = null;response = client.execute(httpPost);//----------判断是否重定向开始int code = response.getStatusLine().getStatusCode();String newuri = "";if (code == 302) {Header header = response.getFirstHeader("location"); // 跳转的目标地址是在 HTTP-HEAD 中的newuri = header.getValue(); // 这就是跳转后的地址,再向这个地址发出新申请,以便得到跳转后的信息是啥。System.out.println(newuri);System.out.println(code);httpPost = new HttpPost(newuri);httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");se = new StringEntity(js);se.setContentType(CONTENT_TYPE_TEXT_JSON);httpPost.setEntity(se);response = client.execute(httpPost);code = response.getStatusLine().getStatusCode();System.out.println("login" + code);}//------------重定向结束HttpEntity entity = null;entity = response.getEntity();String s2 = EntityUtils.toString(entity, "UTF-8");System.out.println(s2);}
}

2.复杂实例,来自网络:

需要引导用户打开授权页面进行授权

1). 直接获取数据,传递用户账号;

2).  没有登陆直接去访问会跳转到登陆页面;

3). 登陆了之后,会有个授权页面,需要手动去点击授权按钮才真正跳转;

/*** <pre>* 模拟需要登陆之后才能访问第三方网站* 并且需要一些人工参与的操作* </pre>*/
public class Test {private String userName = "我是用户名";private String password = "我是密码";public void loginNext() throws IOException {BasicCookieStore cookieStore = new BasicCookieStore();// 全局用这一个httpClient对象模拟真实的一个浏览器中操作CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();try {// 模拟用户登录HttpPost httpLogin = new HttpPost("xxxxxxxxxxxxxx/index.php/auth/auth/login");// 指向一个没有验证码的登录页面List<NameValuePair> nvps = new ArrayList<>();nvps.add(new BasicNameValuePair("username", userName));// 用户名对应的keynvps.add(new BasicNameValuePair("password", MD5Coder.md5Encode(password)));// 密码对应的keyhttpLogin.setEntity(new UrlEncodedFormEntity(nvps));CloseableHttpResponse respLogin = httpClient.execute(httpLogin);try {HttpEntity entity = respLogin.getEntity();out.println("respLogin------------>>" + respLogin.toString());out.println("Login form get: " + respLogin.getStatusLine());EntityUtils.consume(entity);out.println("Initial set of cookies:");List<Cookie> cookies = cookieStore.getCookies();if (cookies.isEmpty()) {out.println("None");} else {for (int i = 0; i < cookies.size(); i++) {out.println("Cookie-" + i + "==" + cookies.get(i).toString());}}} finally {respLogin.close();}// 利用会话保持,继续访问目标地址HttpGet httpGetAuth = new HttpGet("xxxxxxxxxxxxxxx/index.php/Auth/Auth/auth?app_id=xxxxxx&redirect_uri=回调地址&response_type=code");CloseableHttpResponse respAuth = httpClient.execute(httpGetAuth);String entityAuthStr = "";try {out.println(respAuth.getStatusLine());HttpEntity entityAuth = respAuth.getEntity();entityAuthStr = EntityUtils.toString(entityAuth);out.println("get Auth cookies:");List<Cookie> cookies = cookieStore.getCookies();if (cookies.isEmpty()) {out.println("None");} else {for (int i = 0; i < cookies.size(); i++) {out.println("- " + cookies.get(i).toString());}}out.println("访问目标地址的结果--------------------->>" + entityAuthStr);//把结果打印出来看一下EntityUtils.consume(entityAuth);} finally {respAuth.close();}// 解析登陆之后访问目标地址的html页面 获取目标form表单元素Document doc = Jsoup.parseBodyFragment(entityAuthStr);String title = doc.title();out.println("title-------->>" + title);Element element = doc.body();Elements form = element.select("[name='authForm']");// 授权的form表单out.println(form);String actionUrl = form.attr("action");String app_id = element.select("[name='app_id']").val();String redirect_uri = element.select("[name='redirect_uri']").val();String state = element.select("[name='state']").val();String key = element.select("[name='key']").val();String format = element.select("[name='format']").val();// 利用会话保持,继续模拟点击授权按钮 提交form表单HttpPost httpPostGetCode = new HttpPost(actionUrl);List<NameValuePair> nvps2 = new ArrayList<>();nvps2.add(new BasicNameValuePair("app_id", app_id));nvps2.add(new BasicNameValuePair("redirect_uri", redirect_uri));nvps2.add(new BasicNameValuePair("state", state));nvps2.add(new BasicNameValuePair("key", key));nvps2.add(new BasicNameValuePair("format", format));httpPostGetCode.setEntity(new UrlEncodedFormEntity(nvps2));CloseableHttpResponse respGetCode = httpClient.execute(httpPostGetCode);try {HttpEntity entityGetCode = respGetCode.getEntity();out.println("respAuth------------>>" + respGetCode.toString());// 最终目的 获取Location中的url中的某一值Header location = respGetCode.getFirstHeader("Location");out.println("location------------>>" + location.getValue());EntityUtils.consume(entityGetCode);} finally {respGetCode.close();}} finally {httpClient.close();}}
}

HttpClient 重定向 302相关推荐

  1. httpclient如何处理302重定向

    在使用httpclient做接口测试的时候,遇到了一个重定向的接口,由于框架原因导致的必需得重定向到另外一个域名的接口完成功能.在之前未遇到这个的情况,经过修改请求方法解决了这个问题.大致思路是:如果 ...

  2. JAVA核心知识点--HttpClient获取302响应中的Location头信息

    HttpClient获取302响应中的Location头信息 public static String getLocationUrl(String url) {RequestConfig config ...

  3. 重定向 302 与localhost 学习笔记

    1.新建工程: import java.io.IOException; import java.io.PrintWriter;import javax.servlet.ServletException ...

  4. http 302重定向 java_重定向 302 与localhost 学习笔记

    1.新建工程: import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletExceptio ...

  5. java httpclient 重定向_httpclient 中post请求重定向

    背景:使用httpclient 的post请求进行登录,需要重定向登录,请求重定向后的地址 在httpclient中post请求不像get请求自己可以重定向,实现方式是 判断post请求返回码是否是3 ...

  6. java httpclient重定向_处理HttpClient重定向

    我正在将一些数据发布到正在回答302移动临时的服务器上. 我希望HttpClient遵循重定向并自动获取新位置,因为我相信这是HttpClient的默认行为.但是,我得到一个例外,而不是按照重定向:( ...

  7. Spring Security——关闭未认证时重定向(302)到登录页面(loginPage)

    问题描述 当访问该web服务的一个请求 /test 且该请求需要用户认证,那么Spring Security会将请求302到通过 httpSecurity.formLogin().loginPage( ...

  8. java httpclient 重定向_用Apache HttpClient实现URL重定向

    很多网站都使用了URL重定向技术,把一个原始请求从一个位置路由到另一个位置.原因可能是多方面的,比如域名转发.URL缩写.隐私保护.在同一网站维持相似的域名等. 本文讲述怎样使用Apache HTTP ...

  9. java httpclient 重定向_如何在HttpClient中自动重定向(java,apache)

    我创建了httpClient并设置了设置 HttpClient client = new HttpClient(); client.getParams().setCookiePolicy(Cookie ...

最新文章

  1. 【云计算】使用nsenter进入Docker容器进行调试
  2. Ajax的简单实现(JQuary)
  3. 华为交换机端口隔离配置
  4. CentOS系统恢复误删除的文件
  5. mysql同步大师_数据库大师成长日记:您最需要了解的NoSQL非关系型数据库
  6. leetcode450. 删除二叉搜索树中的节点(详解)
  7. (扩展欧几里德算法)zzuoj 10402: C.机器人
  8. MFC线程自定义消息
  9. go interface转int_Go 中 slice 的 In 功能实现探索
  10. [Hive]Hive合并小文件
  11. Fragstats 4.2 批处理(geotiff格式)
  12. Altium Designer安装教程
  13. 涉密计算机清退登记表,涉密载体登记表.doc
  14. 数据存储过程之MySQL与ORACLE数据库的差别
  15. 修改html颜色代码,JavaScript实现更改网页背景与字体颜色的方法
  16. help用法总结(基于材料:“老托福听力93篇”)
  17. 通过文献计量学助您发表高影响因子论文—基于Citespace和vosviewer文献计量学可视化SCI论文高效写作方法
  18. 基础版微信模板消息开发详解,附代码PHP
  19. FBA海运是什么,FBA海运的优势是什么
  20. arm编程语言基础c,ARM基础:ARM 伪指令详解

热门文章

  1. 学习SOA前的几点寻思
  2. Huffman树与Huffman编码
  3. ice storm暴风雪加盟_暴风雪Storm VR中文版-暴风雪VR下载 VR版--pc6下载站
  4. VR丨有哪些靠谱的VR开发工具之引擎篇
  5. MFC中使用COleVariant获取CMFCPropertyGridProperty属性窗口某个属性值
  6. 当Android SDK连接不上夜神模拟器时
  7. 浅析游戏AI的原理与实现
  8. 使用SRI保护你的网站免受第三方CDN恶意攻击
  9. FastDFS分布式文件系统详解
  10. 什么是音箱阻抗与阻尼系数