一定要注意编码,请求时,content-type里的编码,仅仅是流的编码,而结果的编码类型,则是流转化为字符串是需要设定的。

以下是3种使用get/post的方式:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair; /**
* @Description:发送http请求帮助类
*/
public class HttpHelper { /**
* POST请求
*
* @param urlStr 请求地址
* @param params 参数字典
* @param charset 编码,最好传“UTF-8”
* @return
* @exception RuntimeException
*/
public static String sendPostByHttpUrlConnection(String urlStr, Map<String, Object> params, String charset) {
StringBuffer resultBuffer = null;
// 构建请求参数
String sbParams= JoiningTogetherParams(params);
HttpURLConnection con = null;
OutputStreamWriter osw = null;
BufferedReader br = null;
// 发送请求
try {
URL url = new URL(urlStr);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (sbParams != null && sbParams.length() > 0) {
osw = new OutputStreamWriter(con.getOutputStream(), charset);
osw.write(sbParams);
osw.flush();
}
// 读取返回内容
resultBuffer = new StringBuffer();
int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
if (contentLength > 0) {
br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
osw = null;
throw new RuntimeException(e);
} finally {
if (con != null) {
con.disconnect();
con = null;
}
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
} finally {
if (con != null) {
con.disconnect();
con = null;
}
}
}
} return resultBuffer.toString();
} public static String sendPostByUrlConnection(String urlStr, Map<String, Object> params, String charset) {
StringBuffer resultBuffer = null;
// 构建请求参数
String sbParams= JoiningTogetherParams(params);
URLConnection con = null;
OutputStreamWriter osw = null;
BufferedReader br = null;
try {
URL realUrl = new URL(urlStr);
// 打开和URL之间的连接
con = realUrl.openConnection();
// 设置通用的请求属性
con.setRequestProperty("accept", "*/*");
con.setRequestProperty("connection", "Keep-Alive");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
con.setDoOutput(true);
con.setDoInput(true);
// 获取URLConnection对象对应的输出流
osw = new OutputStreamWriter(con.getOutputStream(), charset);
if (sbParams != null && sbParams.length() > 0) {
// 发送请求参数
osw.write(sbParams);
// flush输出流的缓冲
osw.flush();
}
// 定义BufferedReader输入流来读取URL的响应
resultBuffer = new StringBuffer();
int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
if (contentLength > 0) {
br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
osw = null;
throw new RuntimeException(e);
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
}
}
}
return resultBuffer.toString();
} public static String sendGetByHttpUrlConnection(String urlStr, Map<String, Object> params, String charset) {
StringBuffer resultBuffer = null;
// 构建请求参数
String sbParams= JoiningTogetherParams(params);
HttpURLConnection con = null;
BufferedReader br = null;
try {
URL url = null;
if (sbParams != null && sbParams.length() > 0) {
url = new URL(urlStr + "?" + sbParams);
} else {
url = new URL(urlStr);
}
con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.connect();
resultBuffer = new StringBuffer();
br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
} finally {
if (con != null) {
con.disconnect();
con = null;
}
}
}
}
return resultBuffer.toString();
} public static String sendGetByUrlConnection(String urlStr, Map<String, Object> params, String charset) {
StringBuffer resultBuffer = null;
// 构建请求参数
String sbParams= JoiningTogetherParams(params);
BufferedReader br = null;
try {
URL url = null;
if (sbParams != null && sbParams.length() > 0) {
url = new URL(urlStr + "?" + sbParams);
} else {
url = new URL(urlStr);
}
URLConnection con = url.openConnection();
// 设置请求属性
con.setRequestProperty("accept", "*/*");
con.setRequestProperty("connection", "Keep-Alive");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立连接
con.connect();
resultBuffer = new StringBuffer();
br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
}
}
}
return resultBuffer.toString();
} public static String httpClientPost(String urlStr, Map<String, Object> params, String charset) {
StringBuffer resultBuffer = null;
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(urlStr);
// 构建请求参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator<Entry<String, Object>> iterator = params.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, Object> elem = iterator.next();
list.add(new BasicNameValuePair(elem.getKey(), String.valueOf(elem.getValue())));
}
BufferedReader br = null;
try {
if (list.size() > 0) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
httpPost.setEntity(entity);
}
HttpResponse response = client.execute(httpPost);
// 读取服务器响应数据
resultBuffer = new StringBuffer();
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
}
}
}
return resultBuffer.toString();
} public static String httpClientGet(String urlStr, Map<String, Object> params, String charset) {
StringBuffer resultBuffer = null;
HttpClient client = new DefaultHttpClient();
BufferedReader br = null;
// 构建请求参数
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry<String, Object> entry : params.entrySet()) {
sbParams.append(entry.getKey());
sbParams.append("=");
try {
sbParams.append(URLEncoder.encode(String.valueOf(entry.getValue()), charset));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
sbParams.append("&");
}
}
if (sbParams != null && sbParams.length() > 0) {
urlStr = urlStr + "?" + sbParams.substring(0, sbParams.length() - 1);
}
HttpGet httpGet = new HttpGet(urlStr);
try {
HttpResponse response = client.execute(httpGet);
// 读取服务器响应数据
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String temp;
resultBuffer = new StringBuffer();
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
}
}
}
return resultBuffer.toString();
} public static String sendSocketPost(String urlStr, Map<String, Object> params, String charset) {
String result = "";
// 构建请求参数
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry<String, Object> entry : params.entrySet()) {
sbParams.append(entry.getKey());
sbParams.append("=");
sbParams.append(entry.getValue());
sbParams.append("&");
}
}
Socket socket = null;
OutputStreamWriter osw = null;
InputStream is = null;
try {
URL url = new URL(urlStr);
String host = url.getHost();
int port = url.getPort();
if (-1 == port) {
port = 80;
}
String path = url.getPath();
socket = new Socket(host, port);
StringBuffer sb = new StringBuffer();
sb.append("POST " + path + " HTTP/1.1\r\n");
sb.append("Host: " + host + "\r\n");
sb.append("Connection: Keep-Alive\r\n");
sb.append("Content-Type: application/x-www-form-urlencoded; charset=utf-8 \r\n");
sb.append("Content-Length: ").append(sb.toString().getBytes().length).append("\r\n");
// 这里一个回车换行,表示消息头写完,不然服务器会继续等待
sb.append("\r\n");
if (sbParams != null && sbParams.length() > 0) {
sb.append(sbParams.substring(0, sbParams.length() - 1));
}
osw = new OutputStreamWriter(socket.getOutputStream());
osw.write(sb.toString());
osw.flush();
is = socket.getInputStream();
String line = null;
// 服务器响应体数据长度
int contentLength = 0;
// 读取http响应头部信息
do {
line = readLine(is, 0, charset);
if (line.startsWith("Content-Length")) {
// 拿到响应体内容长度
contentLength = Integer.parseInt(line.split(":")[1].trim());
}
// 如果遇到了一个单独的回车换行,则表示请求头结束
} while (!line.equals("\r\n"));
// 读取出响应体数据(就是你要的数据)
result = readLine(is, contentLength, charset);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
osw = null;
throw new RuntimeException(e);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
socket = null;
throw new RuntimeException(e);
}
}
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
is = null;
throw new RuntimeException(e);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
socket = null;
throw new RuntimeException(e);
}
}
}
}
}
return result;
} public static String sendSocketGet(String urlStr, Map<String, Object> params, String charset) {
String result = "";
// 构建请求参数
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry<String, Object> entry : params.entrySet()) {
sbParams.append(entry.getKey());
sbParams.append("=");
sbParams.append(entry.getValue());
sbParams.append("&");
}
}
Socket socket = null;
OutputStreamWriter osw = null;
InputStream is = null;
try {
URL url = new URL(urlStr);
String host = url.getHost();
int port = url.getPort();
if (-1 == port) {
port = 80;
}
String path = url.getPath();
socket = new Socket(host, port);
StringBuffer sb = new StringBuffer();
sb.append("GET " + path + " HTTP/1.1\r\n");
sb.append("Host: " + host + "\r\n");
sb.append("Connection: Keep-Alive\r\n");
sb.append("Content-Type: application/x-www-form-urlencoded; charset=utf-8 \r\n");
sb.append("Content-Length: ").append(sb.toString().getBytes().length).append("\r\n");
// 这里一个回车换行,表示消息头写完,不然服务器会继续等待
sb.append("\r\n");
if (sbParams != null && sbParams.length() > 0) {
sb.append(sbParams.substring(0, sbParams.length() - 1));
}
osw = new OutputStreamWriter(socket.getOutputStream());
osw.write(sb.toString());
osw.flush();
is = socket.getInputStream();
String line = null;
// 服务器响应体数据长度
int contentLength = 0;
// 读取http响应头部信息
do {
line = readLine(is, 0, charset);
if (line.startsWith("Content-Length")) {
// 拿到响应体内容长度
contentLength = Integer.parseInt(line.split(":")[1].trim());
}
// 如果遇到了一个单独的回车换行,则表示请求头结束
} while (!line.equals("\r\n"));
// 读取出响应体数据(就是你要的数据)
result = readLine(is, contentLength, charset);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
osw = null;
throw new RuntimeException(e);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
socket = null;
throw new RuntimeException(e);
}
}
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
is = null;
throw new RuntimeException(e);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
socket = null;
throw new RuntimeException(e);
}
}
}
}
}
return result;
} private static String readLine(InputStream is, int contentLength, String charset) throws IOException {
List<Byte> lineByte = new ArrayList<Byte>();
byte tempByte;
int cumsum = 0;
if (contentLength != 0) {
do {
tempByte = (byte) is.read();
lineByte.add(Byte.valueOf(tempByte));
cumsum++;
} while (cumsum < contentLength);// cumsum等于contentLength表示已读完
} else {
do {
tempByte = (byte) is.read();
lineByte.add(Byte.valueOf(tempByte));
} while (tempByte != 10);// 换行符的ascii码值为10
} byte[] resutlBytes = new byte[lineByte.size()];
for (int i = 0; i < lineByte.size(); i++) {
resutlBytes[i] = (lineByte.get(i)).byteValue();
}
return new String(resutlBytes, charset);
} private static String JoiningTogetherParams(Map<String, Object> params){
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry<String, Object> e : params.entrySet()) {
sbParams.append(e.getKey());
sbParams.append("=");
sbParams.append(e.getValue());
sbParams.append("&");
}
return sbParams.substring(0, sbParams.length() - 1);
}
return "";
}
}

java发起HTTP请求的共用类的更多相关文章

  1. 如何使用HttpClient包实现JAVA发起HTTP请求?

    今天在搭建公司项目框架的时候,发现缺少了一个Java发送HTTP请求的工具类,在网上找了一通,经过自己的改造,已经能实现get请求和post请求的了,现在将代码贴在这里.给大家参考. 1 packag ...

  2. 关于java发起http请求

    我们到底能走多远系列(41) 扯淡: 好久没总结点东西了,技术上没什么总结,感觉做事空牢牢的.最近也比较疲惫. 分享些东西,造福全人类~ 主题: 1,java模拟发起一个http请求 使用HttpUR ...

  3. 用Java发起HTTP请求与获取状态码(含状态码列表)

    转自:https://blog.csdn.net/xyw591238/article/details/51072697 在使用Java请求Web程序比如访问WebService接口时,通常需要先判断访 ...

  4. 通过java发送http请求

    通常的http请求都是由用户点击某个连接或者按钮来发起的,但是在一些后台的Java程序中需要发送一些get或这post请求,因为不涉及前台页面,该怎么办呢? 下面为大家提供一个Java发送http请求 ...

  5. 第三篇 :微信公众平台开发实战Java版之请求消息,响应消息以及事件消息类的封装

    微信服务器和第三方服务器之间究竟是通过什么方式进行对话的? 下面,我们先看下图: 其实我们可以简单的理解: (1)首先,用户向微信服务器发送消息: (2)微信服务器接收到用户的消息处理之后,通过开发者 ...

  6. [Java] 两种发起POST请求方法,并接收返回的响应内容的处理方式

    1.利用apache提供的commons-httpclient-3.0.jar包 代码如下: /** * 利用HttpClient发起POST请求,并接收返回的响应内容 * * @param url ...

  7. java中两种发起POST请求,并接收返回的响应内容的方式  (转)

    http://xyz168000.blog.163.com/blog/static/21032308201162293625569/ 2.利用java自带的java.net.*包下提供的工具类 代码如 ...

  8. MySQL_(Java)使用JDBC向数据库发起查询请求

    MySQL_(Java)使用JDBC向数据库发起查询请求 传送门 MySQL_(Java)使用JDBC创建用户名和密码校验查询方法 传送门 MySQL_(Java)使用preparestatement ...

  9. java如何发起https请求

    1.写一个SSLClient类,继承至HttpClient import java.security.cert.CertificateException; import java.security.c ...

随机推荐

  1. vmworkstation安装unbuntu server 网络配置:NAT模式

    之前安装虚拟机测试环境的时候,习惯了使用桥接模式或者仅主机模式:今天偶然发现,其实NAT 模式的网络配置还是挺方便的. 在新建虚拟机的时候,选择网络模式为NAT,虚拟机创建完成之后,在vmworkst ...

  2. Deep Learning (中文版&英文版)

    Bengio Yoshua,Ian J. Goodfellow 和 Aaron Courville共同撰写的<深度学习>(Deep Learning)是一本为了帮助学生及从业者入门机器学习 ...

  3. sql练习(针对Mysql)

    创建表: DROP TABLE DEPT; --部门表 CREATE TABLE DEPT( DEPTNO int PRIMARY KEY, DNAME ) , --部门名称 LOC ) ---部门地 ...

  4. c++如何解决大数组栈内存不够的问题

    在c++中,我们可以直接通过下面的方式创建一个数组: ; ; ; double phi[N][Nx][Ny]; double phi_b[N][Nx][Ny]; 但是,如果上述的Nx和Ny比较小还好说 ...

  5. ThreadPoolExecutor 中的 shutdown() 、 shutdownNow() 、 awaitTermination() 的用法和区别

    Java并发编程中在使用到ThreadPoolExecutor时,对它的三个关闭方法(shutdown().shutdownNow().awaitTermination())的异同点如下: shutd ...

  6. iconfont 批量把图标加入购物车的方法

    在浏览器中按 f12 打开[开发人员工具],找到[console(控制台)],输入以下代码,再按回车,稍等片刻即可把全部图标加入购物车 var ll = document.getElementsByC ...

  7. [Java初探外篇]__关于时间复杂度与空间复杂度

    前言 我们在前面的排序算法的学习中了解到了,排序算法的分类,效率的比较所使用到的判断标准,就包括时间复杂度和空间复杂度,当时因为这两个定义还是比较难以理解的,所以决定单独开一篇文章,记录一下学习的过程 ...

  8. OSRM笔记

    OSRM OSRM(OpenStreetMap Routeing Machine)可用于路线规划.作为高性能的路线规划引擎,OSRM使用C++14编写,基于开源的OpenStreetMap数据实现. ...

  9. Vue笔记:在项目中使用 SCSS

    背景概述 1. CSS预处理器 css预处理器定义了一种新的编程语言,编译后成正常的CSS文件.为CSS增加一些编程的特性,无需考虑浏览器的兼容问题,让CSS更加简洁,适应性更强,可读性更佳,更易于代 ...

  10. docker(一)

    一.docker 概述 Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的 linux 机器上,也可以实现虚拟化.容器是完全使用沙箱 ...