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 ...
随机推荐
- plotplayer声道设置原声
1.打开plotplayer.根据按键F5,选择声音——>语言/同步/其他-流选择 2.重启plotplayer
- 巨蟒python全栈开发flask2
内容回顾: 上节回顾: Flask .response 三剑客: render_template 模板 redirect 重定向 - URL地址 "" 字符串 HTTPRespon ...
- SQL case when else
先占个坑,sql 版本的swith case SELECT Oldvote, (CASE THEN (SELECT NOW() from dual) END) as "number" ...
- window.onbeforeunload 埋点 页面停留时间
window.onbeforeunload - Web API 接口 | MDN https://developer.mozilla.org/zh-CN/docs/Web/API/Window/onb ...
- Kubernetes网络框架
// cmd/kubelet/app/server.go -1.func UnsecuredKubeletDeps(s *options.KubeletServer) (*kubelet.Kubele ...
- django博客项目3:创建 Django 博客的数据库模型
设计博客的数据库表结构 博客最主要的功能就是展示我们写的文章,它需要从某个地方获取博客文章数据才能把文章展示出来,通常来说这个地方就是数据库.我们把写好的文章永久地保存在数据库里,当用户访问我们的博客 ...
- 使用Ehcache缓存同步启动时抛出异常net.sf.ehcache.CacheException: Can't assign requested address
这个问题在插入公司内网网线的时候不会复现,由于我使用的是公司无线网络,故导致此问题. 具体解决办法是:在启动服务时,指定使用默认ipv4的网络接口.可以在启动jvm时添加参数-Djava.net.pr ...
- Open Source VOIP applications, both clients and servers (开源sip server & sip client 和开发库)
SIP Proxies SBO SIP Proxy Bypass All types of Internet Firewall JAIN-SIP Proxy Mini-SIP-Proxy A very ...
- mysql的-F与master-data理解(一个小型的big-log恢复)
例子: 使用mysqlbin-log恢复,有两种情况,一个是停数据库,一个是不停 在不停数据库的情况下,为了防止新的写入,需要将bin-log切割,然后新的数据会保存在新的bin-log里面 在此之前 ...
- python全栈开发从入门到放弃之列表的内置方法
1.列表切片 l=['a','b','c','d','e','f'] print(l[1:5]) # 根据索引号来切片,但顾头不顾尾 ['b', 'c', 'd', 'e'] print(l[1:5: ...