通过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 ...
随机推荐
- 关于cin的用法一些小结
在写二叉树的时候遇到if(!cin)那几个标志位弄得并不清楚,还遇到了诸如cin.clear()等函数,感觉C++又白学了,于是打算去网上搜了几篇靠谱的文章,有时候看来,一些事件处理类的工程代码,在A ...
- transform和transition
作者:zccst 例如:图片墙 .另外还有,便签墙 使用的样式: 1,正常情况下 ul#index_cards li { background: url("../images/ca ...
- ZOJ 2059 The Twin Towers
双塔DP. dp[i][j]表示前i个物品,分成两堆(可以不全用),价值之差为j的时候,较小一堆的价值为dp[i][j]. #include<cstdio> #include<cst ...
- winscp 秘钥登录
如题 如果不想用密码登录,可以选择用秘钥文件登录winscp 原理和linux分发ssh公钥是一个道理 1:在被管理的机器上分发公钥 ,出现 authorized_keys才可以 完成服务端配置 2: ...
- CSS排序工具csscomb
一. css写久了以后感觉需要按照某种规则或者说顺序来,便于开发和维护.O(∩_∩)O哈哈~ 找到一个 http://csscomb.com/ CSS排序总结: 1. 对css样式排序; 2. 按样式 ...
- bzoj 4383: [POI2015]Pustynia
复习了一下线段树优化建图的姿势,在线段树上连边跑拓扑排序 这题竟然卡vector……丧病 #include <bits/stdc++.h> #define N 1810000 using ...
- Swing 窗口的最小化到系统图标与还原
2014年2月26日 13:01:47 一个上午的功夫,终于折腾好了. 上午主要是卡在监听事件的参数问题.当时脑子不好使,忘记事件是自己构造的,傻傻的测试了半天,如何传递窗口的参数 等中午解决的时候, ...
- SVN:cannot map the project with svn provider解决办法
转自:http://www.blogjava.net/jzone/articles/337697.html 首先,叙述一下令人蛋疼的情况,纠结了我几个小时,更新Workspace原有的项目,显示更新成 ...
- PHP 中 static 和 self 的区别
使用 self:: 或者 __CLASS__ 对当前类的静态引用,取决于定义当前方法所在的类: 使用 static:: 不再被解析为定义当前方法所在的类,而是在实际运行时计算的.也可以称之为" ...
- C#子窗口与父窗口交互(使用委托和事件)
目标:在子窗口Form2上单击按钮时向Form1传递一组自定义参数,并显示在父窗口Form1上. 方法:有很多方法,这里只介绍委托和事件的实现方式. 思路:Form2中定义事件,Form1创建Form ...