java模拟http的get和post请求
如题,使用Java模拟GET和POST请求。使用GET可以实现网页抓取,使用POST可以实现对某些网站登录的暴力破解。不过仅是练习,实际意义不大。
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Map; /**
* HTTP工具
* @author robinzhang
*
*/
public class HttpUtil {
/**
* 请求类型: GET
*/
public final static String GET = "GET";
/**
* 请求类型: POST
*/
public final static String POST = "POST"; /**
* 模拟Http Get请求
* @param urlStr
* 请求路径
* @param paramMap
* 请求参数
* @return
* @throws Exception
*/
public static String get(String urlStr, Map<String, String> paramMap) throws Exception{
urlStr = urlStr + "?" + getParamString(paramMap);
HttpURLConnection conn = null;
try{
//创建URL对象
URL url = new URL(urlStr);
//获取URL连接
conn = (HttpURLConnection) url.openConnection();
//设置通用的请求属性
setHttpUrlConnection(conn, GET);
//建立实际的连接
conn.connect();
//获取响应的内容
return readResponseContent(conn.getInputStream());
}finally{
if(null!=conn) conn.disconnect();
}
} /**
* 模拟Http Post请求
* @param urlStr
* 请求路径
* @param paramMap
* 请求参数
* @return
* @throws Exception
*/
public static String post(String urlStr, Map<String, String> paramMap) throws Exception{
HttpURLConnection conn = null;
PrintWriter writer = null;
try{
//创建URL对象
URL url = new URL(urlStr);
//获取请求参数
String param = getParamString(paramMap);
//获取URL连接
conn = (HttpURLConnection) url.openConnection();
//设置通用请求属性
setHttpUrlConnection(conn, POST);
//建立实际的连接
conn.connect();
//将请求参数写入请求字符流中
writer = new PrintWriter(conn.getOutputStream());
writer.print(param);
writer.flush();
//读取响应的内容
return readResponseContent(conn.getInputStream());
}finally{
if(null!=conn) conn.disconnect();
if(null!=writer) writer.close();
}
} /**
* 读取响应字节流并将之转为字符串
* @param in
* 要读取的字节流
* @return
* @throws IOException
*/
private static String readResponseContent(InputStream in) throws IOException{
Reader reader = null;
StringBuilder content = new StringBuilder();
try{
reader = new InputStreamReader(in);
char[] buffer = new char[1024];
int head = 0;
while( (head=reader.read(buffer))>0 ){
content.append(new String(buffer, 0, head));
}
return content.toString();
}finally{
if(null!=in) in.close();
if(null!=reader) reader.close();
}
} /**
* 设置Http连接属性
* @param conn
* http连接
* @return
* @throws ProtocolException
* @throws Exception
*/
private static void setHttpUrlConnection(HttpURLConnection conn, String requestMethod) throws ProtocolException{
conn.setRequestMethod(requestMethod);
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("Accept-Language", "zh-CN");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
conn.setRequestProperty("Proxy-Connection", "Keep-Alive");
if(null!=requestMethod && POST.equals(requestMethod)){
conn.setDoOutput(true);
conn.setDoInput(true);
}
} /**
* 将参数转为路径字符串
* @param params
* 参数
* @return
*/
private static String getParamString(Map<String, String> paramMap){
if(null==paramMap || paramMap.isEmpty()){
return "";
}
StringBuilder builder = new StringBuilder();
for(String key : paramMap.keySet() ){
builder.append("&")
.append(key).append("=").append(paramMap.get(key));
}
return builder.deleteCharAt(0).toString();
} public static void main(String[] args){
try {
System.out.println( get("http://127.0.0.1/crazy_java.pdf", null) );
} catch (Exception e) {
e.printStackTrace();
}
}
}
java模拟http的get和post请求的更多相关文章
- [Java] 模拟HTTP的Get和Post请求
在之前,写了篇Java模拟HTTP的Get和Post请求的文章,这篇文章起源与和一个朋友砍飞信诈骗网站的问题,于是动用了Apache的comments-net包,也实现了get和post的http请求 ...
- java模拟post请求发送json
java模拟post请求发送json,用两种方式实现,第一种是HttpURLConnection发送post请求,第二种是使用httpclient模拟post请求, 方法一: package main ...
- 上curl java 模拟http请求
最近,我的项目要求java模拟http请求,获得dns解决 tcp处理过的信息特定的连接. java api提供urlConnection apache提供的httpClient都不能胜任该需求,二次 ...
- Java模拟http上传文件请求(HttpURLConnection,HttpClient4.4,RestTemplate)
先上代码: public void uploadToUrl(String fileId, String fileSetId, String formUrl) throws Throwable { St ...
- java模拟http请求(代理ip)
java实现动态切换上网IP (ADSL拨号上网) java动态设置IP java模拟http的Get/Post请求 自动生成IP模拟POST访问后端程序 JAVA 动态替换代理IP并模拟POST
- curl java 模拟http请求
curl java 模拟http请求 直接上代码: public static void main(String args[]) throws Exception { String url = &qu ...
- java模拟http请求
java模拟http发送请求,第一种是HttpURLConnection发送post请求,第二种是使用httpclient模拟post请求, 方法一: package main.utils; impo ...
- java模拟http/https post请求
1.Post请求失败的代码 try { HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = respon ...
- MySQL_(Java)【事物操作】使用JDBC模拟银行转账向数据库发起修改请求
MySQL_(Java)使用JDBC向数据库发起查询请求 传送门 MySQL_(Java)使用JDBC向数据库中插入(insert)数据 传送门 MySQL_(Java)使用JDBC向数据库中删除(d ...
随机推荐
- finereport-JS
JS实现定时刷新报表 setInterval("self.location.reload();",10000); //10000ms即每10s刷新一次页面. 注:对于cpt报表,若 ...
- Powershell About File System
File System Rights Get-Acl $sharepath | select -expand access | where { !$_.IsInherited -AND $_.file ...
- 17.Recflection_反射
www.cnblogs.com/rollenholt/archive/2011/09/02/2163758.html
- table width 决定 td width
w td width 有无在chrome edge ff 均未影响td实际宽度,td接近等比分配table width. <!doctype html> <html lang=&qu ...
- Java程序员面试题集(1-50
下面的内容是对网上原有的Java面试题集及答案进行了全面修订之后给出的负责任的题目和答案,原来的题目中有很多重复题目和无价值的题目,还有不少的参考答案也是错误的,修改后的Java面试题集参照了JDK最 ...
- centos7在vmware上无法上网
centos7在虚拟机中设置NAT后也无法上网! 首先激活网卡!打开桌面右键在终端中打开:cd /etc/sysconfig/network-scripts/ls 找到以ifcfg开头的,如ifcfg ...
- hadoop笔记 基础 归档
核心:分布式存储和分布式计算 闲话: 底层基于socket通信 NIO——java异步io,不阻塞,不等待 bt——p2p软件(点对点传输,每个人既是上传者又是下载者.但是会占用大量网络带宽,所以很多 ...
- C++和JAVA实例化对象的区别
JAVA: A a = new A(); 为A对象创建了一个实例,但在内存中开辟了两块空间:一块空间在堆区,存放new A()这个对象:另一块空间在堆栈,也就是栈,存放a,a的值为new A()这个对 ...
- 五分钟学会 Kotlin 语法
为什么使用Kotlin 项目一期在收尾了终于有时间折腾了,一个多月以来Kotlin从入门到现在,坚持用来开发的切身感受.因为语法与Java的区别挺大的一开始很想放弃,如果不是因为项目在使用,想必很少人 ...
- Linux用户、群组及权限
由于对文件的操作需要切换到相应文件夹下进行,所以对文件内容的修改,最基本的是需要其文件夹执行的权限. 文件夹的读权限(read)可以独立行使,但是对文件夹内容的写权限(对其内文件的新建.删除.重命名) ...