向指定url发送get、post请求工具类示例
2017-11-28 16:09
639 查看
public class HttpUtil {
public static final String POST = "POST";
public static final String GET = "GET";
/**
* 向指定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;
String urlNameString = "";
try {
if(StringUtils.isNotBlank(param)) {
urlNameString = url + "?" + param;
} else {
urlNameString = url;
}
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.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("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
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;
}
public static String sendGet(String url) {
return sendGet(url,null);
}
/**
* 重定向
* @param httpServletRequest
* @param httpServletResponse
* @param url
*/
public static void redirectUrl(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,String url){
try {
httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + url);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 模拟Post表单提交 带文件和参数
* @param serverUrl 请求地址
* @param paramsMap 请求参数
* @param filePath 文件路径 如 e:\\test.jpg
* @return
* @throws Exception
*/
public static String sendHttpPostRequest(String serverUrl,
Map<String,String> paramsMap,String filePath){
// 每个post参数之间的分隔。随意设定,只要不会和其他的字符串重复即可。
String boundary = "----------HV2ymHFg03ehbqgZCaKO6jyH";
String end = "\r\n";
String twoHyphens = "--";
String strResponse = "";
OutputStream out = null;
InputStream in = null;
try {
// 向服务器发送post请求
URL url = new URL(serverUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 发送POST请求必须设置如下两行
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
// 头
// String boundary = boundary;
// 传输内容
StringBuffer contentBody = new StringBuffer(twoHyphens + boundary);
// 尾
String endboundary = end+twoHyphens+boundary+twoHyphens+end;
out = connection.getOutputStream();
// 1. 处理文字形式的POST请求
for (Entry<String, String> map : paramsMap.entrySet()){
contentBody.append(end)
.append("Content-Disposition: form-data; name=\"")
.append(map.getKey() + "\"")
.append(end)
.append(end)
.append(map.getValue())
.append(end)
.append(twoHyphens)
.append(boundary);
}
String boundaryMessage1 = contentBody.toString();
out.write(boundaryMessage1.getBytes("utf-8"));
// 2. 处理文件上传
contentBody = new StringBuffer();
contentBody.append(end)
.append("Content-Disposition:form-data; name=\"")
.append( "file\"; ") // form中field的名称
.append("filename=\"")
.append(filePath+ "\"") // 上传文件的文件名,包括目录
.append(end)
.append("Content-Type:application/octet-stream")
.append(end)
.append(end);
String boundaryMessage2 = contentBody.toString();
out.write(boundaryMessage2.getBytes("utf-8"));
// 开始真正向服务器写文件
File file = new File(filePath);
DataInputStream dis = new Dat
a3ff
aInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[(int) file.length()];
bytes = dis.read(bufferOut);
out.write(bufferOut, 0, bytes);
dis.close();
contentBody.append(twoHyphens+boundary);
String boundaryMessage = contentBody.toString();
out.write(boundaryMessage.getBytes("utf-8"));
out.write((twoHyphens+boundary+twoHyphens+end).getBytes("UTF-8"));
// 3. 写结尾
out.write(endboundary.getBytes("utf-8"));
out.flush();
out.close();
// 4. 从服务器获得回答的内容
String strLine = "";
in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
while ((strLine = reader.readLine()) != null) {
strResponse += strLine;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return strResponse;
}
/**
* https GET请求
* @param url
* @param charset
* @return
*/
public static String sendGetHttps(String url, String charset) {
if (null == charset) {
charset = "utf-8";
}
HttpClient httpClient = null;
HttpGet httpGet = null;
String result = null;
try {
httpClient = new SSLClient();
httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, charset);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* https POST请求
* @param url
* @param map
* @param charset
* @return
*/
public static String sendPostHttps(String url, Map<String, String> map, String charset) {
if (null == charset) {
charset = "utf-8";
}
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try {
httpClient = new SSLClient();
httpPost = new HttpPost(url);
//设置参数
List<NameValuePair> list = new ArrayList<>();
if (map != null) {
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
}
}
if (list.size() > 0) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, charset);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
public static final String POST = "POST";
public static final String GET = "GET";
/**
* 向指定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;
String urlNameString = "";
try {
if(StringUtils.isNotBlank(param)) {
urlNameString = url + "?" + param;
} else {
urlNameString = url;
}
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.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("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
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;
}
public static String sendGet(String url) {
return sendGet(url,null);
}
/**
* 重定向
* @param httpServletRequest
* @param httpServletResponse
* @param url
*/
public static void redirectUrl(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,String url){
try {
httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + url);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 模拟Post表单提交 带文件和参数
* @param serverUrl 请求地址
* @param paramsMap 请求参数
* @param filePath 文件路径 如 e:\\test.jpg
* @return
* @throws Exception
*/
public static String sendHttpPostRequest(String serverUrl,
Map<String,String> paramsMap,String filePath){
// 每个post参数之间的分隔。随意设定,只要不会和其他的字符串重复即可。
String boundary = "----------HV2ymHFg03ehbqgZCaKO6jyH";
String end = "\r\n";
String twoHyphens = "--";
String strResponse = "";
OutputStream out = null;
InputStream in = null;
try {
// 向服务器发送post请求
URL url = new URL(serverUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 发送POST请求必须设置如下两行
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
// 头
// String boundary = boundary;
// 传输内容
StringBuffer contentBody = new StringBuffer(twoHyphens + boundary);
// 尾
String endboundary = end+twoHyphens+boundary+twoHyphens+end;
out = connection.getOutputStream();
// 1. 处理文字形式的POST请求
for (Entry<String, String> map : paramsMap.entrySet()){
contentBody.append(end)
.append("Content-Disposition: form-data; name=\"")
.append(map.getKey() + "\"")
.append(end)
.append(end)
.append(map.getValue())
.append(end)
.append(twoHyphens)
.append(boundary);
}
String boundaryMessage1 = contentBody.toString();
out.write(boundaryMessage1.getBytes("utf-8"));
// 2. 处理文件上传
contentBody = new StringBuffer();
contentBody.append(end)
.append("Content-Disposition:form-data; name=\"")
.append( "file\"; ") // form中field的名称
.append("filename=\"")
.append(filePath+ "\"") // 上传文件的文件名,包括目录
.append(end)
.append("Content-Type:application/octet-stream")
.append(end)
.append(end);
String boundaryMessage2 = contentBody.toString();
out.write(boundaryMessage2.getBytes("utf-8"));
// 开始真正向服务器写文件
File file = new File(filePath);
DataInputStream dis = new Dat
a3ff
aInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[(int) file.length()];
bytes = dis.read(bufferOut);
out.write(bufferOut, 0, bytes);
dis.close();
contentBody.append(twoHyphens+boundary);
String boundaryMessage = contentBody.toString();
out.write(boundaryMessage.getBytes("utf-8"));
out.write((twoHyphens+boundary+twoHyphens+end).getBytes("UTF-8"));
// 3. 写结尾
out.write(endboundary.getBytes("utf-8"));
out.flush();
out.close();
// 4. 从服务器获得回答的内容
String strLine = "";
in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
while ((strLine = reader.readLine()) != null) {
strResponse += strLine;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return strResponse;
}
/**
* https GET请求
* @param url
* @param charset
* @return
*/
public static String sendGetHttps(String url, String charset) {
if (null == charset) {
charset = "utf-8";
}
HttpClient httpClient = null;
HttpGet httpGet = null;
String result = null;
try {
httpClient = new SSLClient();
httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, charset);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* https POST请求
* @param url
* @param map
* @param charset
* @return
*/
public static String sendPostHttps(String url, Map<String, String> map, String charset) {
if (null == charset) {
charset = "utf-8";
}
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try {
httpClient = new SSLClient();
httpPost = new HttpPost(url);
//设置参数
List<NameValuePair> list = new ArrayList<>();
if (map != null) {
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
}
}
if (list.size() > 0) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, charset);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
相关文章推荐
- 向指定URL发送POST或GET请求工具类-JAVA项目
- java网络编程中向指定URL发送GET POST请求示例
- java网络编程中向指定URL发送GET POST请求示例
- java网络编程中向指定URL发送GET POST请求示例
- 向指定URL发送GET、POST方法的请求
- 向指定URL发送GET或POST请求(调第三方接口)
- 安卓如何向指定URL发送get和post请求
- 向指定URL发送GET POST方法的请求 以及乱码的解决
- Android例子—HttpURLConnection发送POST、GET请求代码示例
- java 实现向指定URL发送get 和 post 请求
- 向指定 URL 发送GET,POST方法的请求(传入指定url和参数,服务器返回字符串数据)
- 向指定URL发送GET,POST方法的请求
- java 向指定URL发送GET、POST方法的请求
- java 向指定 URL 发送Get\Post方法的请求
- Http学习之使用HttpURLConnection发送post和get请求(1)
- 使用URLConnection发送GET和POST请求的简单示例
- Http学习之使用HttpURLConnection发送post和get请求
- HttpUrlConnection用get和post请求发送参数
- 【java发送GET/POST请求工具类】
- java发送post和get请求(1)---HttpURLConnection方式