近期做项目中,须要把消息通过中间件的形式通过http请求的方式推送给第三方,因此用到了http协议,小编花费了一个多小时。对于http协议中的post和get请求,封装了一个工具类。以下与大家分享一下。

有不好的地方请多多不吝赐教。

/**
* @FileName: HttpTest.java
* @Package:com.io
* @Description: TODO
* @author: LUCKY
* @date:2016年1月6日 下午3:49:28
* @version V1.0
*/
package com.io; import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import com.alibaba.common.lang.StringUtil; /**
* @ClassName: HttpTest
* @Description: 自己開始封装的HTTP连接工具,http连接传递的參数封装到一个对象里面,
* http中get请求时,是把參数拼接到url后面的,而post请求直接输出就可以
* @author: LUCKY
* @date:2016年1月6日 下午3:49:28
*/
public class HttpTest { private static final String METHOD_POST = "POST";
private static final String METHOD_GET = "GET";
private static final String DEFAULT_CHARSET = "UTF-8";
private static final String HTTPS = "https";
private static final String TLS = "tls";
private static final String CTYPE = "application/x-www-form-urlencoded;charset="
+ DEFAULT_CHARSET; public static void main(String[] args) throws Exception {
Map<String, String> param = new HashMap<String, String>();
param.put("body", String.valueOf(System.currentTimeMillis()));
param.put("tag", "撒点粉");
String string = doGet(
" http://localhost/receive.do", param,
3000, 3000);
String aa = doPost(
" http://localhost/receive.do", param,
3000, 3000);
System.out.println(string.length());
System.out.println(string);
} /**
* @throws Exception
* @Title: doPost
* @Description: doPost发送请求操作
* @param @param url
* @param @param params
* @param @param readTimeOut
* @param @param connectTimeOut
* @param @return
* @return String
* @throws
*/
public static String doPost(String url, Map<String, String> params,
int readTimeOut, int connectTimeOut) throws Exception {
HttpURLConnection connection = null;
OutputStream out = null;
String result = null;
try {
connection = getConnection(new URL(url), readTimeOut,
connectTimeOut, METHOD_POST, CTYPE, null);
byte[] content = new byte[0];
String param = getUrl(params, DEFAULT_CHARSET);
if (StringUtil.isNotEmpty(param)) {
content = param.getBytes(DEFAULT_CHARSET);
}
out = connection.getOutputStream();
// post传送消息内容
out.write(content);
// 接受的返回值通过buffer来接受 result = responseAsString(connection);
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
if (connection != null) {
connection.disconnect();
}
} return result; } /**
* @Title: doGet
* @Description: doGet发送消息请求
* @param @param url
* @param @param params
* @param @param readTimeOut
* @param @param connectTimeOut
* @param @return
* @return String
* @throws
*/
public static String doGet(String url, Map<String, String> params,
int readTimeOut, int connectTimeOut) { HttpURLConnection connection = null;
String result=null;
try {
String query = getUrl(params, DEFAULT_CHARSET);
connection = getConnection(new URL(buildUrl(url, query)),
readTimeOut, connectTimeOut, METHOD_GET, CTYPE, null);
result=responseAsString(connection);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
return result;
} // 把doGet和doPost请求最后的接受參数再次的抽取出来
private static String responseAsString(HttpURLConnection connection) {
StringBuffer buffer = new StringBuffer();
InputStreamReader reader = null;
OutputStream out = null;
try {
// 假设返回成功
if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
reader = new InputStreamReader(connection.getInputStream());
char[] ch = new char[1024];
int x = 0;
while ((x = reader.read(ch)) != -1) {
buffer.append(ch, 0, x);
}
} } catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
} return buffer.toString();
} // 须要再写一个getConnection的方法,把doPost和doGet的connection都抽取出来
private static HttpURLConnection getConnection(URL url, int readTimeOut,
int connectTimeOut, String method, String ctype,
Map<String, String> headMap) throws Exception {
HttpURLConnection connection = null;
if (url == null) {
return null;
}
if (HTTPS.equals(url.getProtocol())) {
SSLContext ctx = null;
try {
ctx = SSLContext.getInstance(TLS);
ctx.init(new KeyManager[0],
new TrustManager[] { new DefaultTrustManager() },
new SecureRandom());
} catch (Exception e) {
throw new IOException(e);
}
HttpsURLConnection connHttps = (HttpsURLConnection) url
.openConnection();
connHttps.setSSLSocketFactory(ctx.getSocketFactory());
connHttps.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) {
return true;
}
});
connection = connHttps;
} else {
connection = (HttpURLConnection) url.openConnection();
} connection.setReadTimeout(readTimeOut);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod(method);
connection.setConnectTimeout(connectTimeOut);
connection.setRequestProperty("Accept",
"text/xml,text/javascript,text/html");
connection.setRequestProperty("User-Agent", "top-sdk-java");
connection.setRequestProperty("Content-Type", ctype);
// 遍历设置headMap
if (null != headMap) {
Set<Entry<String, String>> entries = headMap.entrySet();
for (Map.Entry<String, String> entry : entries) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
} return connection;
} /**
* @Title: getUrl
* @Description: doGet发送请求时拼接的URL
* @param @param params
* @param @param charset
* @param @return
* @param @throws UnsupportedEncodingException
* @return String
* @throws
*/
public static String getUrl(Map<String, String> params, String charset)
throws UnsupportedEncodingException {
StringBuffer buffer = new StringBuffer("?");
if (params == null && params.isEmpty()) {
return null;
}
// 否则的话,開始拼接须要传递的值。也就是URL?AA==BB&CC==EE这种相似的连接值
Set<Entry<String, String>> entries = params.entrySet();
for (Entry<String, String> entry : entries) {
String name = entry.getKey();
String value = entry.getValue();
// 还须要进行一次推断是否为空,一定要慎重
if (StringUtil.isNotEmpty(name) && StringUtil.isNotEmpty(value)) {
// 假设不为空的话。開始进行连接操作
buffer.append("&").append(name).append("=")
.append(URLEncoder.encode(value, charset));
} }
return buffer.toString().substring(0, buffer.toString().length() - 1); } /**
* @Title: buildUrl
* @Description: 拼接url地址操作
* @param @param url
* @param @param query
* @param @return
* @return String
* @throws
*/
private static String buildUrl(String url, String query) {
if (query == null && query.isEmpty()) {
return url;
}
if (url.endsWith("?")) {
url = url + query;
} else {
url = url + "? " + query;
} return url;
} private static class DefaultTrustManager implements X509TrustManager { public X509Certificate[] getAcceptedIssuers() {
return null;
} public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
} public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
} }

很多其它有关http协议的内容,请參考:Http协议具体解释

Http协议中的Content-Type

Java中发送http的get、post请求的更多相关文章

  1. JAVA中发送电子邮件的方法

    JAVA中发送邮件的方法不复杂,使用sun的JavaMail的架包就可以实现.  一.下载JavaMail的架包,并导入项目中,如下: 二.附上代码例子,如下: 1.在main函数中对各项参数进行赋值 ...

  2. Java中解决前端的跨域请求问题

    在最近的分布式项目中,由于前端需要向后台请求数据,但不是同一个域名的,常用的ajax方法并不能成功调用,索然后台有数据返回,但是并不能被前端正常解析. 于是便查询知道了后台返回的数据格式的问题.不能用 ...

  3. 在Java中发送http的post请求,设置请求参数等等

    前几天做了一个定时导入数据的接口,需要发送http请求,第一次做这种的需求,特地记一下子, 导包 import java.text.SimpleDateFormat;import java.util. ...

  4. java中发送http请求的方法

    package org.jeecgframework.test.demo; import java.io.BufferedReader; import java.io.FileOutputStream ...

  5. java代码发送JSON格式的httpPOST请求

    package com.test; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOE ...

  6. (转)java代码发送JSON格式的httpPOST请求

    import Java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import j ...

  7. spring MVC 管理HttpClient---实现在java中直接向Controller发送请求

    在spring MVC中,大多数时候是由客户端的页面通过ajax等方式向controller发送请求,但有时候需要在java代码中直接向controller发送请求,这时可以使用HttpCilent实 ...

  8. JAVA Socket 实现HTTP与HTTPS客户端发送POST与GET方式请求

    JAVA Socket 实现HTTP与HTTPS客户端发送POST与GET方式请求 哇,一看标题怎么这么长啊,其实意思很简单,哥讨厌用HTTP Client做POST与GET提交 觉得那个毕竟是别人写 ...

  9. java中模拟http(https)请求的工具类

    在java中,特别是java web中,我们经常需要碰到的一个场景是我们需要从服务端去发送http请求,获取到数据,而不是直接从浏览器输入请求网址获得相应.比如我们想访问微信接口,获取其返回信息. 在 ...

随机推荐

  1. 洛谷P2770 航空路线问题 最小费用流

    Code: #include<cstdio> #include<iostream> #include<algorithm> #include<vector&g ...

  2. [HDU5686]2016"百度之星" - 资格赛 Problem B

    题目大意:给你n,规定一个串中相邻的两个1可以合并为一个2(别的不行),让你求长度为n的全1串最多能变成多少种不同的串. 解题思路:我们先来找一波规律,发现n=1,2,3,4,5时答案分别为1,2,3 ...

  3. 大O时间复杂度

    大O表示法指出了在最糟情况下的运行时间.比较操作数,指出了算法运行时间的增速 常见的大O运行时间 O(logn):也叫对数时间,包括二分查找 O(n):也叫线性时间,包括简单查找 O(nlogn):包 ...

  4. C语言中头文件尖括号和引号的区别

    用include 引用头文件时,双引号和尖括号的区别: 1.双引号:引用非标准库的头文件,编译器首先在程序源文件所在目录查找,如果未找到,则去系统默认目录查找,通常用于引用用户自定义的头文件. 2.尖 ...

  5. 国庆 day 2 下午

    最大值(max) Time Limit:1000ms   Memory Limit:128MB 题目描述 LYK有一本书,上面有很多有趣的OI问题.今天LYK看到了这么一道题目: 这里有一个长度为n的 ...

  6. Dynamics CRM2013 Form利用window.location.reload()进行全局刷新带来的问题及解决的方法

    CRM2013以后.表单的保存后变成了局部刷新而非全局刷新,但非常多情况下我们须要刷新整个页面.通过刷新页面来使脚本运行或者业务规则运行来实现某些业务效果,一般我们会使用window.location ...

  7. 【Android UI】案例02 圆角边框、圆角背景的实现(shape)

    本文主要分享圆角边框与圆角背景的实现方式.该方式的实现,须要了解shape的使用.该部分的具体介绍,请阅读博客http://blog.csdn.net/mahoking/article/details ...

  8. HDU1232 畅通project 并查集

    这道题跟HDU 1213 How Many Tables 并查集很接近,都是赤裸裸的并查集的题. 思路:如果还须要建n-1条路.每并一次就自减1. 參考代码: #include<stdio.h& ...

  9. python判断一个单词是否为有效的英文单词?——三种方法

    For (much) more power and flexibility, use a dedicated spellchecking library like PyEnchant. There's ...

  10. 43.$http

    转自:https://www.cnblogs.com/best/tag/Angular/ $http 是 AngularJS 中的一个核心服务,用于读取远程服务器的数据. 使用格式: // 简单的 G ...