java模拟浏览器发送请求
package test; import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder; import javax.servlet.http.HttpServletRequest; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils; public class TestRequestUtil {
// public static void main(String[] args) {
// doGetStr("http://dzdzwxcs1.ciitc.com.cn/s/VcbrYFtK");
// }
/**
* 接口调用 GET
*/
public static void httpURLConectionGET(String urls) {
try {
URL url = new URL(urls); // 把字符串转换为URL请求地址
HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
connection.connect();// 连接会话
// 获取输入流
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {// 循环读取流
sb.append(line); //写入对象中
}
br.close();// 关闭流
connection.disconnect();// 断开连接
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
System.out.println("请求失败!");
}
} /**
* 接口调用 POST
*/
public static void httpURLConnectionPOST(String urls) {
try {
URL url = new URL(urls); // 将url 以 open方法返回的urlConnection 连接强转为HttpURLConnection连接 (标识一个url所引用的远程对象连接)
HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 此时cnnection只是为一个连接对象,待连接中 // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)
connection.setDoOutput(true); // 设置连接输入流为true
connection.setDoInput(true); // 设置请求方式为post
connection.setRequestMethod("POST"); // post请求缓存设为false
connection.setUseCaches(false); // 设置该HttpURLConnection实例是否自动执行重定向
connection.setInstanceFollowRedirects(true); // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)
// application/x-javascript text/xml->xml数据 application/x-javascript->json对象
// application/x-www-form-urlencoded->表单数据
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
connection.connect(); // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
String parm = "storeId=" + URLEncoder.encode("32", "utf-8"); // URLEncoder.encode()方法 为字符串进行编码 // 将参数输出到连接
dataout.writeBytes(parm); // 输出完成后刷新并关闭流
dataout.flush();
dataout.close(); // 重要且易忽略步骤 (关闭流,切记!) System.out.println(connection.getResponseCode()); // 连接发起请求,处理服务器响应 (从连接获取到输入流并包装为bufferedReader)
BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream()));
@SuppressWarnings("unused")
String line = null;
StringBuilder sb = new StringBuilder(); // 用来存储响应数据 // 循环读取流,若不到结尾处
while ((line = bf.readLine()) != null) {
sb.append(bf.readLine());
}
bf.close(); // 重要且易忽略步骤 (关闭流,切记!)
connection.disconnect(); // 销毁连接
System.out.println(sb.toString()); } catch (Exception e) {
e.printStackTrace();
}
} /**
* get 请求 @param @param url @return String @throws
*/
public static String doGetStr(String url) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
String result = ""; try {
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity, "UTF-8");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
HttpClientUtils.closeQuietly(httpClient);
}
return result;
} /**
* post 请求 @param @param url @param @param outStr @throws
*/
public static String doPostStr(String url, String outStr) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost();
String result = ""; try {
httpPost.setEntity(new StringEntity(outStr, "UTF-8"));
HttpResponse response = httpClient.execute(httpPost);
result = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
HttpClientUtils.closeQuietly(httpClient);
}
return result;
}
}
以上是个人根据网上总结的几种请求方法。
java模拟浏览器发送请求的更多相关文章
- 使用HttpClient配置代理服务器模拟浏览器发送请求调用接口测试
在调用公司的某个接口时,直接通过浏览器配置代理服务器可以请求到如下数据: 请求url地址:http://wwwnei.xuebusi.com/rd-interface/getsales.jsp?cid ...
- Java基础教程——模拟浏览器发送请求
JAVA访问网页 分别测试使用get和post方法访问网页,可以收到服务器的请求,并写入到html文件中. import java.io.*; import java.net.*; import ja ...
- java 模拟浏览器发送post请求
java使用URLConnection发送post请求 /** * 向指定 URL 发送POST方法的请求 * * @param url * 发送请求的 URL * @param param * 请求 ...
- telnet客户端模拟浏览器发送请求
telnet 客户端 telnet客户端能够发出请求去连接服务器(模拟浏览器) 使用telnet之前,需要开启telnet客户端 1.进入控制面板 2.进入程序和功能,选择打开或关闭windows功能 ...
- 20200726_java爬虫_使用HttpClient模拟浏览器发送请求
浏览器获取数据: 打开浏览器 ==> 输入网址 ==> 回车查询 ==> 返回结果 ==> 浏览器显示结果数据 HttpClient获取数据: 创建HttpClient ==& ...
- htmlunit爬虫工具使用--模拟浏览器发送请求,获取JS动态生成的页面内容
Htmlunit是一款模拟浏览抓取页面内容的java框架,具有js解析引擎(rhino),可以解析页面的js脚本,得到完整的页面内容,特殊适合于这种非完整页面的站点抓取. 下载地址: https:// ...
- java模拟浏览器包selenium整合了htmlunit,火狐浏览器,IE浏览器,opare浏览器驱
//如果网页源码中有些内容是js渲染过来的,那你通过HttpClient直接取肯定取不到,但是这些数据一般都是通过异步请求传过来的(一般都是通过ajax的get或者post方式).那么你可以通过火狐浏 ...
- 浏览器与服务器交互原理以及用java模拟浏览器操作v
浏览器应用服务器JavaPHPApache * 1,在HTTP的WEB应用中, 应用客户端和服务器之间的状态是通过Session来维持的, 而Session的本质就是Cookie, * 简单的讲,当浏 ...
- httpClient模拟浏览器发请求
一.介绍 httpClient是Apache公司的一个子项目, 用来提高高效的.最新的.功能丰富的支持http协议的客户端编程工具包.完成可以模拟浏览器发起请求行为. 二.简单使用例子 : 模拟浏览器 ...
随机推荐
- shell脚本报错 value too great for base
此错误是shell脚本在计算以0开头的数字时,默认以8进制进行计算,导致在计算08时超过了8进制的范围,报此错误. shell脚本代码如下: #!/bin/bash a= ..} do a=$[$a+ ...
- PAT 1071. Speech Patterns
又是考输入输出 #include <cstdio> #include <cstdlib> #include <string> #include <vector ...
- ASP.NET MVC中,前台DropDownList传值给后台。
List<SelectListItem> ZH = new List<SelectListItem>(); ZH.Add(new SelectListItem { Text = ...
- c#开源项目收集
1百度云高速下载c#开源: https://github.com/ResourceHunter/BaiduPanDownloadWinform 2.IdaCsharp http://idacsharp ...
- inline-block元素,在同一行上下显示
两个元素使用了inline-block,并列显示时,会上下显示,给人感觉不在同一行 原因:其中一个元素使用了overflow:hidden,导致了基线变更 解决:1.另一个元素也添加overflow: ...
- 如何修改settings.xml的镜像
今天在下载一个maven依赖包时候,下载后一直显示的是upload的jar包,然后检查了下自己的settings.xml配置,发现依赖的还是以前的内网nexus得配置.所以下载不下来,现在改为ali的 ...
- Linq批量建表
public JsonResult CreateTable() { db = new RZBDbContext(); var query = (from c in db.Clients select ...
- freess(未测试)
freess 使用 nodejs 配合 shadowsocks-windows 实现FQ (windows) 使用方法: 如果你没有安装nodejs请先安装,访问 https://nodejs.org ...
- Azure 中 Linux 虚拟机的大小
本文介绍可用于运行 Linux 应用和工作负荷的 Azure 虚拟机的可用大小与选项. 此外,还提供在计划使用这些资源时要考虑的部署注意事项. 本文也适用于 Windows 虚拟机. 类型 大小 说明 ...
- mysql 配置详解
[client]port = 3306socket = /tmp/mysql.sock [mysqld]port = 3306socket = /tmp/mysql.sock basedir = /u ...