/*
传字符串类型参数
*/
package com.jiliele.utils;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONException;
public class RestfulHelper {
private final String ConnectServer = “http://jdpower.jidongcloud.com:8080/minelee”;
static RestfulHelper rfh_instance = null;
private static Logger log = Logger.getLogger(RestfulHelper.class
.getClass());
public static RestfulHelper getInstance() {
if (rfh_instance == null) {
rfh_instance = new RestfulHelper();
}
return rfh_instance;
}
//funName表示返回值变量,data表示请求参数变量
public String rerequest(String funName,String data) {
String processURL = ConnectServer + "/"+funName;
String result22 = "";
try {
//请求体
StringEntity entity = new StringEntity(data,
HTTP.UTF_8);
// 创建httpPost远程连接实例
HttpPost httpPost = new HttpPost(processURL);
httpPost.addHeader("Content-Type", "application/json");
httpPost.setEntity(entity);
// 创建httpClient实例
HttpClient client = new DefaultHttpClient();
//以下是响应*************
HttpResponse response;
log.info("---"+funName+"----request----processURL=" + processURL
+ "----" + data.toString());
//执行远程调用之后或得的结果
response = client.execute(httpPost);
//http响应体的内容(http响应流形式的结果)
HttpEntity entitys = response.getEntity();
result22 = EntityUtils.toString(entitys, "UTF-8");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
result22 = "NULL_1";
log.error("---"+funName+"----FAILED----", e);
} catch (IOException e) {
// TODO Auto-generated catch block
result22 = "NULL_2";
log.error("---"+funName+"----FAILED----", e);
} catch (JSONException e) {
// TODO Auto-generated catch block
log.error("---"+funName+"----FAILED----", e);
result22 = "NULL_3";
}
log.info("---"+funName+"----response----" + result22);
return result22;
}
}
/*
传map集合类型参数
*/
package com.bjpowernode.p2p.common.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpEntity;
public class HttpClientUtils {
/**
* Get 请求方法
*
* @param url
* @return
*/
public static String doGet(String url) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
try {
// 通过址默认配置创建一个httpClient实例
httpClient = HttpClients.createDefault();
// 创建httpGet远程连接实例
HttpGet httpGet = new HttpGet(url);
// 设置配置请求参数
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
.setConnectionRequestTimeout(35000)// 请求超时时间
.setSocketTimeout(60000)// 数据读取超时时间
.build();
// 为httpGet实例设置配置
httpGet.setConfig(requestConfig);
// 执行get请求得到返回对象
response = httpClient.execute(httpGet);
// 通过返回对象获取返回数据
HttpEntity entity = response.getEntity();
// 通过EntityUtils中的toString方法将结果转换为字符串
result = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 关闭资源
if (null != response) {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return result;
}
// map集合形式传参,paramMap是请求参数
public static String doPost(String url, Map<String, Object> paramMap) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
try {
// 创建httpClient实例
httpClient = HttpClients.createDefault();
// 创建httpPost远程连接实例
HttpPost httpPost = new HttpPost(url);
// 配置请求参数实例
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
.setConnectionRequestTimeout(35000)// 设置连接请求超时时间
.setSocketTimeout(60000)// 设置读取数据连接超时时间
.build();
// 为httpPost实例设置配置
httpPost.setConfig(requestConfig);
// 封装post请求参数
if (null != paramMap && paramMap.size() > 0) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
// 通过map集成entrySet方法获取entity
Set<Map.Entry<String, Object>> entrySet = paramMap.entrySet();
// 循环遍历,获取迭代器
Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> mapEntry = iterator.next();
nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
}
// 为httpPost设置封装好的请求参数
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
}
// 执行post请求得到返回对象
response = httpClient.execute(httpPost);
// 通过返回对象获取数据
HttpEntity entity = response.getEntity();
// 将返回的数据转换为字符串
result = EntityUtils.toString(entity);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != response) {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return result;
}
public static String doPostByXml(String url, String requestDataXml) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
try {
// 创建httpClient实例
httpClient = HttpClients.createDefault();
// 创建httpPost远程连接实例
HttpPost httpPost = new HttpPost(url);
// 配置请求参数实例
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
.setConnectionRequestTimeout(35000)// 设置连接请求超时时间
.setSocketTimeout(60000)// 设置读取数据连接超时时间
.build();
// 为httpPost实例设置配置
httpPost.setConfig(requestConfig);
httpPost.setEntity(new StringEntity(requestDataXml, "UTF-8"));
httpPost.addHeader("Content-Type", "text/xml");
/*
* //封装post请求参数 if (null != paramMap && paramMap.size() > 0) {
* List<NameValuePair> nvps = new ArrayList<NameValuePair>();
* //通过map集成entrySet方法获取entity Set<Map.Entry<String, Object>>
* entrySet = paramMap.entrySet(); //循环遍历,获取迭代器
* Iterator<Map.Entry<String, Object>> iterator =
* entrySet.iterator(); while (iterator.hasNext()) {
* Map.Entry<String, Object> mapEntry = iterator.next();
* nvps.add(new BasicNameValuePair(mapEntry.getKey(),
* mapEntry.getValue().toString())); }
*
* //为httpPost设置封装好的请求参数 httpPost.setEntity(new
* UrlEncodedFormEntity(nvps, "UTF-8")); }
*/
// 执行post请求得到返回对象
response = httpClient.execute(httpPost);
// 通过返回对象获取数据
HttpEntity entity = response.getEntity();
// 将返回的数据转换为字符串
result = EntityUtils.toString(entity);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != response) {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return result;
}
/**
* 带参数并指定编码的POST请求
*
* @param url
* @param paramMap
* @param encode
* @return
* @throws UnsupportedEncodingException
*/
public static String doPostByEncode(String url, Map<String, Object> paramMap, String charset)
throws UnsupportedEncodingException {
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
// 创建httpClient连接对象
httpClient = HttpClients.createDefault();
// 创建post请求连接对象
HttpPost httpPost = new HttpPost(url);
// 创建连接请求参数对象,并设置连接参数
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(15000) // 连接服务器主机超时时间
.setConnectionRequestTimeout(60000) // 连接请求超时时间
.setSocketTimeout(60000) // 设置读取响应数据超时时间
.build();
// 为httpPost请求设置参数
httpPost.setConfig(requestConfig);
// 判断参数是否为空
if (null != paramMap && paramMap.size() > 0) {
List<NameValuePair> nvpsList = new ArrayList<NameValuePair>();
// 将map集成转换为Set集合
Set<Map.Entry<String, Object>> entrySet = paramMap.entrySet();
// 通过EntrySet集合获取迭代器
Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
// 循环遍历
while (iterator.hasNext()) {
// 遍历下一个
Map.Entry<String, Object> mapEntry = iterator.next();
nvpsList.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
}
// 将请求参数添加到post请求参数对象中
// new UrlEncodedFormEntity(nvpsList, charset):将输入的参数指定成合适的字符集
httpPost.setEntity(new UrlEncodedFormEntity(nvpsList, charset));
}
String result = "";
try {
// httpClient对象执行post请求,并返回响应参数对象
httpResponse = httpClient.execute(httpPost);
// 从响应对象中获取响应内容
HttpEntity entity = httpResponse.getEntity();
result = EntityUtils.toString(entity);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
续工具类
package base.sendMes;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class HttpsRequest {
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestProperty("Charset", "UTF-8");
// 建立实际的连接
connection.connect();
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
//conn.setRequestProperty("user-agent","Fiddler");
//conn.setRequestProperty("Accept", "application/json");
//conn.setRequestProperty("Content-Type","application/json;charset=utf-8");
//conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("content-Type", "application/json");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
// out = new PrintWriter(conn.getOutputStream());
byte[] requestStringBytes = param.getBytes("UTF-8");
OutputStream outputStream = conn.getOutputStream();
outputStream.write(requestStringBytes);
outputStream.close();
/*
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();*/
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
private static void httpUrlConnection() {
try {
String pathUrl = "http://sms.zh-ink.com/api/sms/send";
// 建立连接
URL url = new URL(pathUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
// //设置连接属性
httpConn.setDoOutput(true);// 使用 URL 连接进行输出
httpConn.setDoInput(true);// 使用 URL 连接进行输入
httpConn.setUseCaches(false);// 忽略缓存
httpConn.setRequestMethod("POST");// 设置URL请求方法
String requestString = "{\"uid\": \"kehu\", \"userpwd\": \"62c8ad0a15d9d1ca38d5dee762a16e01\", \"mobile\": \"18191279586\", \"message\": \"【中核英科】您的验证码:22342\", \"ext\": \"111\"}";
// 设置请求属性
// 获得数据字节数据,请求数据流的编码,必须和下面服务器端处理请求流的编码一致
byte[] requestStringBytes = requestString.getBytes("UTF-8");
httpConn.setRequestProperty("Content-length", "" + requestStringBytes.length);
httpConn.setRequestProperty("Content-Type", "application/json");
httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
httpConn.setRequestProperty("Charset", "UTF-8");
//
// 建立输出流,并写入数据
OutputStream outputStream = httpConn.getOutputStream();
outputStream.write(requestStringBytes);
outputStream.close();
// 获得响应状态
int responseCode = httpConn.getResponseCode();
if (HttpURLConnection.HTTP_OK == responseCode) {// 连接成功
// 当正确响应时处理数据
StringBuffer sb = new StringBuffer();
String readLine;
BufferedReader responseReader;
// 处理响应流,必须与服务器响应流输出的编码一致
responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
while ((readLine = responseReader.readLine()) != null) {
sb.append(readLine).append("\n");
}
responseReader.close();
System.out.print("返回结果:" + sb.toString());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args){
httpUrlConnection();
}
}