一、工具类

package com.alpha.util;import net.sf.json.JSONObject;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import weaver.general.BaseBean;import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;public class HttpRestful extends BaseBean {/*** post提交接口* * @param url* @param params* @return*/public static String postHttp(String url, Map<String, Object> params) {String responseMsg = "";HttpClient httpClient = new HttpClient();httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");PostMethod postMethod = new PostMethod(url);Set<String> keys = params.keySet();for (String str : keys) {postMethod.addParameter(str, params.get(str).toString());}try {httpClient.executeMethod(postMethod);ByteArrayOutputStream out = new ByteArrayOutputStream();InputStream in = postMethod.getResponseBodyAsStream();int len = 0;byte[] buf = new byte[1024];while ((len = in.read(buf)) != -1) {out.write(buf, 0, len);}responseMsg = out.toString("UTF-8");} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {postMethod.releaseConnection();}return responseMsg;}/*** get提交接口* * @param url* @return*/public static String getHttp(String url) {String responseMsg = "";HttpClient httpClient = new HttpClient();GetMethod getMethod = new GetMethod(url);getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());//getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");//getMethod.setRequestHeader("Accept", "application/json");try {httpClient.executeMethod(getMethod);ByteArrayOutputStream out = new ByteArrayOutputStream();InputStream in = getMethod.getResponseBodyAsStream();int len = 0;byte[] buf = new byte[1024];while ((len = in.read(buf)) != -1) {out.write(buf, 0, len);}responseMsg = out.toString("UTF-8");} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {// 释放连接getMethod.releaseConnection();}return responseMsg;}/*** put 提交* * @param url*            地址* @param** @throws UnsupportedEncodingException */public static  String putHttp(String url) throws UnsupportedEncodingException {//String str = "{\"billId\":\"444444\",\"status\":\"1\"}";DefaultHttpClient httpClient = new DefaultHttpClient();//List<NameValuePair> listpara = new ArrayList<NameValuePair>(); //listpara.add(new BasicNameValuePair("billId","HF-QMYX-FLXHC(CSXM)2-20180710"));//listpara.add(new BasicNameValuePair("status","1"));//UrlEncodedFormEntity formentity = new UrlEncodedFormEntity(listpara, "utf-8");StringBuilder result = new StringBuilder();try {//String b = new String(str.getBytes("ISO-8859-1"), "UTF-8");HttpPut putRequest = new HttpPut(url);putRequest.addHeader("Content-Type","application/json;charset=UTF-8");putRequest.addHeader("Accept", "application/json");//JSONObject keyArg = new JSONObject();//keyArg.put("value1", newValue);// keyArg.put("value2", newValue2);//StringEntity input = null;//putRequest.setEntity(formentity);HttpResponse response = httpClient.execute(putRequest);if (response.getStatusLine().getStatusCode() != 200) {throw new RuntimeException("Failed : HTTP error code : "+ response.getStatusLine().getStatusCode());}BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));String output;while ((output = br.readLine()) != null) {result.append(output);}} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return result.toString();}/*** 原生态json post提交http接口* * @param url* @param obj* @return* @throws Exception*/public static String sendConn(String url, JSONObject obj) throws Exception {org.apache.http.client.HttpClient client = new DefaultHttpClient();HttpPost post = new HttpPost(url);post.setHeader("Content-Type", "application/json");post.addHeader("Authorization", "Basic YWRtaW46");String result = "";try {StringEntity s = new StringEntity(obj.toString(), "utf-8");s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));post.setEntity(s);// 发送请求HttpResponse httpResponse = client.execute(post);// 获取响应输入流InputStream inStream = httpResponse.getEntity().getContent();BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));StringBuilder strber = new StringBuilder();String line = null;while ((line = reader.readLine()) != null)strber.append(line + "\n");inStream.close();result = strber.toString();System.out.println(result);if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {System.out.println("请求服务器成功,做相应处理");} else {System.out.println("请求服务端失败");}} catch (Exception e) {System.out.println("请求异常");throw new RuntimeException(e);}return result;}public Map<String, Object> jsopStr2Map(String str) {Map<String, Object> result = new HashMap<String, Object>();JSONObject json = JSONObject.fromObject(str);result = json;return result;}
public static String sendConn(String urlstr,String method,String paramstr) {if ("GET".equals(method.toUpperCase())) {urlstr += "?" + paramstr;}String results="";try {URL url = new URL(urlstr);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod(method.toUpperCase());// 提交模式// conn.setConnectTimeout(10000);//连接超时 单位毫秒// conn.setReadTimeout(2000);//读取超时 单位毫秒conn.setDoOutput(true);// 是否输入参数// 表单参数与get形式一样if (!"GET".equals(method.toUpperCase())) {StringBuffer params = new StringBuffer();params.append(paramstr);byte[] bypes = params.toString().getBytes();conn.getOutputStream().write(bypes);// 输入参数}InputStream in = conn.getInputStream();byte[] tempbytes = new byte[1024]; // 读写速度ByteArrayOutputStream out = new ByteArrayOutputStream();int c;while ((c = in.read(tempbytes)) != -1) {out.write(tempbytes, 0, c);}results = out.toString();out.flush();out.close();conn = null;return results;} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return results;}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.connect();// 获取所有响应头字段Map<String, List<String>> map = connection.getHeaderFields();// 遍历所有的响应头字段for (String key : map.keySet()) {// System.out.println(key + "--->" + map.get(key));}// 定义 BufferedReader输入流来读取URL的响应in = new BufferedReader(new InputStreamReader(connection.getInputStream()));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;
}public static void main(String[] args) throws Exception {}}

二、实际使用方式

package com.alpha.util;import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
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.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;
import net.sf.json.JSONObject;import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;import weaver.conn.RecordSet;
import weaver.file.multipart.FilePart;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.swfa.AmountUtil;public class KaoQinUtilNew extends BaseBean {/*** post提交接口* * @param url* @param params* @return*/public static String postHttp(String url, Map<String, Object> params) {String responseMsg = "";HttpClient httpClient = new HttpClient();httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");PostMethod postMethod = new PostMethod(url);Set<String> keys = params.keySet();for (String str : keys) {postMethod.addParameter(str, params.get(str).toString());}try {httpClient.executeMethod(postMethod);ByteArrayOutputStream out = new ByteArrayOutputStream();InputStream in = postMethod.getResponseBodyAsStream();int len = 0;byte[] buf = new byte[1024];while ((len = in.read(buf)) != -1) {out.write(buf, 0, len);}responseMsg = out.toString("UTF-8");} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {postMethod.releaseConnection();}return responseMsg;}/*** get提交接口* * @param url* @return*/public static String getHttp(String url) {String responseMsg = "";HttpClient httpClient = new HttpClient();GetMethod getMethod = new GetMethod(url);getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());//getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");//getMethod.setRequestHeader("Accept", "application/json");try {httpClient.executeMethod(getMethod);ByteArrayOutputStream out = new ByteArrayOutputStream();InputStream in = getMethod.getResponseBodyAsStream();int len = 0;byte[] buf = new byte[1024];while ((len = in.read(buf)) != -1) {out.write(buf, 0, len);}responseMsg = out.toString("UTF-8");} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {// 释放连接getMethod.releaseConnection();}return responseMsg;}/*** put 提交* * @param url*            地址* @param* @throws UnsupportedEncodingException */public static  String putHttp(String url) throws UnsupportedEncodingException {//String str = "{\"billId\":\"444444\",\"status\":\"1\"}";DefaultHttpClient httpClient = new DefaultHttpClient();//List<NameValuePair> listpara = new ArrayList<NameValuePair>(); //listpara.add(new BasicNameValuePair("billId","HF-QMYX-FLXHC(CSXM)2-20180710"));//listpara.add(new BasicNameValuePair("status","1"));//UrlEncodedFormEntity formentity = new UrlEncodedFormEntity(listpara, "utf-8");StringBuilder result = new StringBuilder();try {//String b = new String(str.getBytes("ISO-8859-1"), "UTF-8");HttpPut putRequest = new HttpPut(url);putRequest.addHeader("Content-Type","application/json;charset=UTF-8");putRequest.addHeader("Accept", "application/json");//JSONObject keyArg = new JSONObject();//keyArg.put("value1", newValue);// keyArg.put("value2", newValue2);//StringEntity input = null;//putRequest.setEntity(formentity);HttpResponse response = httpClient.execute(putRequest);if (response.getStatusLine().getStatusCode() != 200) {throw new RuntimeException("Failed : HTTP error code : "+ response.getStatusLine().getStatusCode());}BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));String output;while ((output = br.readLine()) != null) {result.append(output);}} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return result.toString();}/*** 原生态json post提交http接口* * @param url* @param obj* @return* @throws Exception*/public static String sendConn(String url, JSONObject obj) throws Exception {org.apache.http.client.HttpClient client = new DefaultHttpClient();HttpPost post = new HttpPost(url);post.setHeader("Content-Type", "application/json");post.addHeader("Authorization", "Basic YWRtaW46");String result = "";try {StringEntity s = new StringEntity(obj.toString(), "utf-8");s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));post.setEntity(s);// 发送请求HttpResponse httpResponse = client.execute(post);// 获取响应输入流InputStream inStream = httpResponse.getEntity().getContent();BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));StringBuilder strber = new StringBuilder();String line = null;while ((line = reader.readLine()) != null)strber.append(line + "\n");inStream.close();result = strber.toString();System.out.println(result);if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {System.out.println("请求服务器成功,做相应处理");} else {System.out.println("请求服务端失败");}} catch (Exception e) {System.out.println("请求异常");throw new RuntimeException(e);}return result;}public Map<String, Object> jsopStr2Map(String str) {Map<String, Object> result = new HashMap<String, Object>();JSONObject json = JSONObject.fromObject(str);result = json;return result;}
public static String sendConn(String urlstr,String method,String paramstr) {if ("GET".equals(method.toUpperCase())) {urlstr += "?" + paramstr;}String results="";try {URL url = new URL(urlstr);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod(method.toUpperCase());// 提交模式// conn.setConnectTimeout(10000);//连接超时 单位毫秒// conn.setReadTimeout(2000);//读取超时 单位毫秒conn.setDoOutput(true);// 是否输入参数// 表单参数与get形式一样if (!"GET".equals(method.toUpperCase())) {StringBuffer params = new StringBuffer();params.append(paramstr);byte[] bypes = params.toString().getBytes();conn.getOutputStream().write(bypes);// 输入参数}InputStream in = conn.getInputStream();byte[] tempbytes = new byte[1024]; // 读写速度ByteArrayOutputStream out = new ByteArrayOutputStream();int c;while ((c = in.read(tempbytes)) != -1) {out.write(tempbytes, 0, c);}results = out.toString();out.flush();out.close();conn = null;return results;} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return results;}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.connect();// 获取所有响应头字段Map<String, List<String>> map = connection.getHeaderFields();// 遍历所有的响应头字段for (String key : map.keySet()) {// System.out.println(key + "--->" + map.get(key));}// 定义 BufferedReader输入流来读取URL的响应in = new BufferedReader(new InputStreamReader(connection.getInputStream()));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;
}
public static boolean delFile(String localpath){boolean falg = false;File file = new File(localpath);  //加载文件if(file.isFile()&& file.exists()){ //文件是否存在file.delete(); //删除文件falg = true;    }else{falg = true;}return falg;}public static void main(String[] args) throws Exception {// get的获取String jsonstr = getHttp("http:/192.168.1.1/api/finance/getbilllist?status=0");System.out.println(jsonstr);// put的修改     System.out.println(putHttp("http://192.168.1.1/api/finance/updatestatus?billId=HF-QMYX-TYFLJXC-20180701&status=1"));System.out.println(delFile("E:/KwDownload/测试1.pdf"));//提交postString url="http://192.168.1.1:8088/fdc_itf/SetDaili/saveCompany.htm";Map<String, String> dataMap = new HashMap<String, String>();List<Map<String, String>> datalist = new ArrayList<Map<String,String>>();dataMap.put("company_name", "西安有限公司");dataMap.put("company_code", "27583");dataMap.put("pk_company", "38");dataMap.put("pk_project", "集团西北区域");datalist.add(dataMap);Map<String, Object> m = new HashMap<String, Object>();String data = JSONArray.fromObject(datalist).toString();m.put("data", data);String result = postHttp(url,m);System.out.println(result);// 注意这边使用的是commons-httpclient-3.1.jar 架包// 文件下载String responseMsg = "";HttpClient httpClient = new HttpClient();httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");PostMethod postMethod = new PostMethod("http://192.168.1.1/file/upload");
//String filename = "测试测试"; File file = new File("E:/销售费用.xls");postMethod.addParameter("file", "E:/销售费用.xls");postMethod.addParameter("filename", "销售费用");try {httpClient.executeMethod(postMethod);ByteArrayOutputStream out = new ByteArrayOutputStream();InputStream in = postMethod.getResponseBodyAsStream();int len = 0;byte[]buf = newbyte[1024];while ((len = in.read(buf)) != -1){out.write(buf, 0, len);}responseMsg = out.toString("UTF-8");System.out.println(responseMsg);} catch (HttpException e){e.printStackTrace();}catch (IOException e){e.printStackTrace();}finally{postMethod.releaseConnection();}}}

HttpRestful工具类相关推荐

  1. java日期转化工具类

    package com.rest.ful.utils;import java.text.DateFormat; import java.text.ParseException; import java ...

  2. java数据类型相互转换工具类

    package com.rest.ful.utils;import java.util.ArrayList; import java.util.HashMap; import java.util.Li ...

  3. 客快物流大数据项目(五十六): 编写SparkSession对象工具类

    编写SparkSession对象工具类 后续业务开发过程中,每个子业务(kudu.es.clickhouse等等)都会创建SparkSession对象,以及初始化开发环境,因此将环境初始化操作封装成工 ...

  4. [JAVA EE] Thymeleaf 常用工具类

    Thymeleaf 提供了丰富的表达式工具类,例如: #strings:字符串工具类 #dates:时间操作和时间格式化 #numbers:格式化数字对象的方法 #bools:常用的布尔方法 #str ...

  5. httpclient工具类,post请求发送json字符串参数,中文乱码处理

    在使用httpclient发送post请求的时候,接收端中文乱码问题解决. 正文: 我们都知道,一般情况下使用post请求是不会出现中文乱码的.可是在使用httpclient发送post请求报文含中文 ...

  6. spring boot 文件上传工具类(bug 已修改)

    以前的文件上传都是之前前辈写的,现在自己来写一个,大家可以看看,有什么问题可以在评论中提出来. 写的这个文件上传是在spring boot 2.0中测试的,测试了,可以正常上传,下面贴代码 第一步:引 ...

  7. SharePreference工具类

    安卓开发一般都需要进行数据缓存,常用操作老司机已为你封装完毕,经常有小伙伴问怎么判断缓存是否可用,那我告诉你,你可以用这份工具进行存储和查询,具体可以查看源码,现在为你开车,Demo传送门. 站点 S ...

  8. java录排名怎么写_面试官:Java排名靠前的工具类你都用过哪些?

    你知道的越多,不知道的就越多,业余的像一棵小草! 你来,我们一起精进!你不来,我和你的竞争对手一起精进! 编辑:业余草 推荐:https://www.xttblog.com/?p=5158 在Java ...

  9. 【转】 Android快速开发系列 10个常用工具类 -- 不错

    原文网址:http://blog.csdn.net/lmj623565791/article/details/38965311 转载请标明出处:http://blog.csdn.net/lmj6235 ...

最新文章

  1. 06-Windows Server 2012 新特性 ---- Hyper-V实时迁移
  2. [Android1.6]继承BaseAdapter为GridView设置数据时设置setLayoutParams时注意
  3. 多目标函数 matlab 粒子群_【LIBSVM】基于群智能优化算法的支持向量机 (SVM) 参数优化...
  4. 【redis】redis基础命令,分布式锁,缓存问题学习大集合
  5. c语言如何输出一维数组字母,C语言一维数组初步学习笔记
  6. Maven是个什么鬼?,没办法起床排bug...
  7. 30.Linux/Unix 系统编程手册(上) -- 线程:线程同步
  8. 奇幻电影《诛仙I》影评数据分析
  9. 计算机辅助设计和制造论文,计算机辅助设计与制造CAD-CAM
  10. 《结构分析的有限元法与MATLAB程序设计》笔记
  11. [渝粤教育] 郑州轻工业大学 马克思主义基本原理概论 参考 资料
  12. 数据结构 在顺序表中头插及尾插的实现
  13. java爬虫实战——实现简单的爬取网页数据
  14. 物联网卡开启养老新模式
  15. 美丽的夕阳(小孩文章)
  16. CF1774C. Ice and Fire
  17. 福州华侨中学计算机老师,三尺讲台著妙笔 谱写侨习好韶光——记2015级福州华侨中学实习队工作检查...
  18. MATLAB控制系统仿真与CAD
  19. Win10没有安全选项卡怎么办 安全选项卡在哪里
  20. 传奇GOM引擎——添加装备内观特效

热门文章

  1. 计算机高级属性启用玻璃,“win键+tab键无法使用”的解决方案
  2. #三分法判断单峰函数最值#附加例题LA 5009
  3. 原生js获取指定标签的父元素
  4. C语言—猜数字游戏的实现
  5. 工信部总工程师:建设网络强国振兴实体经济
  6. 高中信息技术python及答案_高中信息技术《Python语言》模块试卷.doc
  7. 如何撩学计算机的小哥哥,撩小哥哥的套路句子 这些金句绝对让你一撩一个准...
  8. vue-router back 返回时携带参数
  9. 沙盒在源代码防泄露领域的表现分析
  10. 阿里巴巴内推电话面试