手机膜+东莞网站建设,竞价推广渠道,软件项目管理总结,商标代理公司Java 纯HTTP Get请求获取响应内容#xff0c;如果发生302重定向#xff0c;继而模拟请求域获取重定向后的响应内容。关键点#xff1a;设置conn.setInstanceFollowRedirects为false即可示例代码public static void main(String[] args) {try {StringBuffer buffer new Stri…Java 纯HTTP Get请求获取响应内容如果发生302重定向继而模拟请求域获取重定向后的响应内容。关键点设置conn.setInstanceFollowRedirects为false即可示例代码public static void main(String[] args) {try {StringBuffer buffer new StringBuffer();String url http://localhost:8080/istock/login?unameppass;System.out.println(访问地址: url);//发送get请求URL serverUrl new URL(url);HttpURLConnection conn (HttpURLConnection) serverUrl.openConnection();conn.setRequestMethod(GET);//必须设置false否则会自动redirect到重定向后的地址conn.setInstanceFollowRedirects(false);conn.addRequestProperty(Accept-Charset, UTF-8;);conn.addRequestProperty(User-Agent, Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Firefox/3.6.8);conn.addRequestProperty(Referer, http://matols.com/);conn.connect();//判定是否会进行302重定向if (conn.getResponseCode() 302) {//如果会重定向保存302重定向地址以及Cookies,然后重新发送请求(模拟请求)String location conn.getHeaderField(Location);String cookies conn.getHeaderField(Set-Cookie);serverUrl new URL(location);conn (HttpURLConnection) serverUrl.openConnection();conn.setRequestMethod(GET);conn.setRequestProperty(Cookie, cookies);conn.addRequestProperty(Accept-Charset, UTF-8;);conn.addRequestProperty(User-Agent,Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Firefox/3.6.8);conn.addRequestProperty(Referer, http://matols.com/);conn.connect();System.out.println(跳转地址: location);}//将返回的输入流转换成字符串InputStream inputStream conn.getInputStream();InputStreamReader inputStreamReader new InputStreamReader(inputStream,utf-8);BufferedReader bufferedReader new BufferedReader(inputStreamReader);String str null;while ((str bufferedReader.readLine()) ! null) {buffer.append(str);}bufferedReader.close();inputStreamReader.close();// 释放资源inputStream.close();inputStream null;System.out.println(buffer.toString());} catch (Exception e) {e.printStackTrace();}}相关文章