通过java.net.URLConnection发送HTTP请求的方法
一.前言
如何通过Java发送HTTP请求,通俗点讲,如何通过Java(模拟浏览器)发送HTTP请求。
Java有原生的API可用于发送HTTP请求,即java.net.URL、java.net.URLConnection,这些API很好用、很常用,但不够简便;
所以,也流行有许多Java HTTP请求的framework,如,Apache的HttpClient。
目前项目主要用到Java原生的方式,所以,这里主要介绍此方式。
二.运用原生Java Api发送简单的Get请求、Post请求步骤
- 通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection)
- 设置请求的参数
- 发送请求
- 以输入流的形式获取返回内容
- 关闭输入流
三.发送请求与接收响应流类 HttpRequestor
package me.http; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map; public class HttpRequestor { private String charset = "utf-8";
private Integer connectTimeout = null;
private Integer socketTimeout = null;
private String proxyHost = null;
private Integer proxyPort = null; /**
* Do GET request
* @param url
* @return
* @throws Exception
* @throws IOException
*/
public String doGet(String url) throws Exception { URL localURL = new URL(url); URLConnection connection = this.openConnection(localURL);
HttpURLConnection httpURLConnection = (HttpURLConnection)connection; httpURLConnection.setRequestProperty("Accept-Charset", charset);
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
String tempLine = null;
//响应失败
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
} try {
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader); while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
} } finally { if (reader != null) {
reader.close();
} if (inputStreamReader != null) {
inputStreamReader.close();
} if (inputStream != null) {
inputStream.close();
} } return resultBuffer.toString();
} /**
* Do POST request
* @param url
* @param parameterMap
* @return
* @throws Exception
*/
public String doPost(String url, Map parameterMap) throws Exception { /* Translate parameter map to parameter date string */
StringBuffer parameterBuffer = new StringBuffer();
if (parameterMap != null) {
Iterator iterator = parameterMap.keySet().iterator();
String key = null;
String value = null;
while (iterator.hasNext()) {
key = (String)iterator.next();
if (parameterMap.get(key) != null) {
value = (String)parameterMap.get(key);
} else {
value = "";
} parameterBuffer.append(key).append("=").append(value);
if (iterator.hasNext()) {
parameterBuffer.append("&");
}
}
} System.out.println("POST parameter : " + parameterBuffer.toString()); URL localURL = new URL(url); URLConnection connection = this.openConnection(localURL);
HttpURLConnection httpURLConnection = (HttpURLConnection)connection; httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Accept-Charset", charset);
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterBuffer.length())); OutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
String tempLine = null; try {
outputStream = httpURLConnection.getOutputStream();
outputStreamWriter = new OutputStreamWriter(outputStream); outputStreamWriter.write(parameterBuffer.toString());
outputStreamWriter.flush();
//响应失败
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
}
//接收响应流
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader); while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
} } finally { if (outputStreamWriter != null) {
outputStreamWriter.close();
} if (outputStream != null) {
outputStream.close();
} if (reader != null) {
reader.close();
} if (inputStreamReader != null) {
inputStreamReader.close();
} if (inputStream != null) {
inputStream.close();
} } return resultBuffer.toString();
} private URLConnection openConnection(URL localURL) throws IOException {
URLConnection connection;
if (proxyHost != null && proxyPort != null) {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
connection = localURL.openConnection(proxy);
} else {
connection = localURL.openConnection();
}
return connection;
} /**
* Render request according setting
* @param request
*/
private void renderRequest(URLConnection connection) { if (connectTimeout != null) {
connection.setConnectTimeout(connectTimeout);
} if (socketTimeout != null) {
connection.setReadTimeout(socketTimeout);
} } /*
* Getter & Setter
*/
public Integer getConnectTimeout() {
return connectTimeout;
} public void setConnectTimeout(Integer connectTimeout) {
this.connectTimeout = connectTimeout;
} public Integer getSocketTimeout() {
return socketTimeout;
} public void setSocketTimeout(Integer socketTimeout) {
this.socketTimeout = socketTimeout;
} public String getProxyHost() {
return proxyHost;
} public void setProxyHost(String proxyHost) {
this.proxyHost = proxyHost;
} public Integer getProxyPort() {
return proxyPort;
} public void setProxyPort(Integer proxyPort) {
this.proxyPort = proxyPort;
} public String getCharset() {
return charset;
} public void setCharset(String charset) {
this.charset = charset;
} }
四.为测试方便,新建一个项目,并新建一个Servlet,接收post请求并对HttpRequestor请求响应,发出响应流
LoginServlet.java代码:此处使用了
注解:@WebServlet("/LoginServlet"),也可以在web.xml配置Servlet
package me.loginServlet; import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class LoginServlet
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("111");
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String username = request.getParameter("username");
String blog = request.getParameter("blog"); System.out.println(username);
System.out.println(blog); response.setContentType("text/plain; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
//响应流
response.getWriter().write("It is ok!"); } }
五.测试类Test.java
package me.http; import java.util.HashMap;
import java.util.Map; public class Test {
public static void main(String[] args) {
/* Post Request */
Map dataMap = new HashMap();
dataMap.put("username", "Nick Huang");
dataMap.put("blog", "IT");
try {
System.out.println(new HttpRequestor().doPost("http://localhost:8081/TestProgect2/LoginServlet", dataMap));
//System.out.println(new HttpRequestor().doGet("http://localhost:8081/TestProgect2/LoginServlet"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} /* Get Request */ }
}
1.接收post请求类LoginServlet,控制台测试结果
2.HttpRequestor接收LoginServlet返回的流
OK,完成
六.对于接收TestProgect2项目中LoginServlet.java类返回的流,在真实环境中可能是异步接收返回的流的,当一台机器A向另外一台机器B发送请求,B接收到A的信息,将信息处理后,需要将处理结果返回即响应返回给A,A会接收到B返回的信息
可以另外建一个Servlet类HttpListenerServlet.java来专门异步接收返回的信息
package me.http; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class HttpListenerServlet
*/
@WebServlet("/HttpListenerServlet")
public class HttpListenerServlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public HttpListenerServlet() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
InputStream inputStream = null;
inputStream = request.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
String tempLine = null;
StringBuffer resultBuffer=new StringBuffer();
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
} System.out.println(resultBuffer.toString());
} }
最后感谢这位博主的博文:http://www.cnblogs.com/nick-huang/p/3859353.html
通过java.net.URLConnection发送HTTP请求的方法的更多相关文章
- Java学习笔记--通过java.net.URLConnection发送HTTP请求
http://www.cnblogs.com/nick-huang/p/3859353.html 使用Java API发送 get请求或post请求的步骤: 1. 通过统一资源定位器(java.net ...
- 通过java.net.URLConnection发送HTTP请求(原生、爬虫)
目录 1. 运用原生Java Api发送简单的Get请求.Post请求 2. 简单封装 3. 简单测试 如何通过Java发送HTTP请求,通俗点讲,如何通过Java(模拟浏览器)发送HTTP请求.Ja ...
- 使用java.net.URLConnection发送http请求
首先,这个需要一点HTTP基础,可以先看个书了解下,我看的<http权威指南>的前4章,后面道行不够看不下去. 然后我们的是java.net的接口: 几个类的API: package co ...
- java 模拟浏览器发送post请求
java使用URLConnection发送post请求 /** * 向指定 URL 发送POST方法的请求 * * @param url * 发送请求的 URL * @param param * 请求 ...
- 发送http请求的方法
在http/1.1 协议中,定义了8种发送http请求的方法 get post options head put delete trace connect patch. 根据http协议的设计初衷,不 ...
- 【JAVA】通过URLConnection/HttpURLConnection发送HTTP请求的方法(一)
Java原生的API可用于发送HTTP请求 即java.net.URL.java.net.URLConnection,JDK自带的类: 1.通过统一资源定位器(java.net.URL)获取连接器(j ...
- 使用URLConnection发送http请求实现简单爬虫(可以配置代理)
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import jav ...
- java 实现HttpRequest 发送http请求
package com.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStr ...
- UrlConnection发送http请求 中文乱码解决
中文乱码 DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream()); //dos.writeBytes(jsonD ...
随机推荐
- ecos的setting
类似windows的注册表 数据是存储在kvstore中的 当通过key在kvstore中取不到数据,会加载app/$app_name/setting.php,在setting.php中查找,找到后放 ...
- 使用node-livereload自动刷新页面
1. 安装node 2. 安装python 3. 安装connect, serve-static和node-livereload (以下都假设命令行当前目录为e:\WebSite) e:\WebSit ...
- CodeForces 625A Guest From the Past
贪心水题 #include <stdio.h> #include <algorithm> #include <string.h> #include <queu ...
- (简单) HDU 5154 Harry and Magical Computer,图论。
Description In reward of being yearly outstanding magic student, Harry gets a magical computer. When ...
- Spring AOP进行日志记录,管理
在java开发中日志的管理有很多种.我一般会使用过滤器,或者是Spring的拦截器进行日志的处理.如果是用过滤器比较简单,只要对所有的.do提交进行拦截,然后获取action的提交路径就可以获取对每个 ...
- Vue.js使用前
下载安装 node,npm,git 安装cnpm 淘宝cnpm镜像https://npm.taobao.org/,-g表示进行全局安装 npm install -g cnpm --registry=h ...
- 【转】15款Java程序员必备的开发工具
如果你是一名Web开发人员,那么用膝盖想也知道你的职业生涯大部分将使用Java而度过.这是一款商业级的编程语言,我们没有办法不接触它. 对于Java,有两种截然不同的观点:一种认为Java是最简单功能 ...
- Django performance
Reference: https://impythonist.wordpress.com/2016/02/21/building-high-performance-django-systems/ Th ...
- Linux_System11
1.查看/var目录的大小:1)ll -hd /var 查看目录的实际大小2)du -sh /var 查看目录所占磁盘空间大小修改权限:chmod 750 hunan修改属主和属组:groupadd ...
- Objective-C中的Hello World
Objective-C在C语言的基础之上,加入了自己的一些独特的特性,而且在Objective-C中兼容C语言原有的用法.在Objective-C中,实现Hello World和C语言有一定的区别,如 ...