代码:


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;public class HttpUtils {static Logger logger = Logger.getLogger(HttpUtils.class);public static JSONObject httpGet(String urlStr) throws Exception {URL url = new URL(urlStr);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setRequestProperty("Content-Type", "text/json;charset=utf-8");BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));StringBuffer buf = new StringBuffer();String inputLine = in.readLine();while (inputLine != null) {buf.append(inputLine).append("\r\n");inputLine = in.readLine();}in.close();//return new JSONObject(buf.toString().trim());}public static String httpGet1(String urlStr) throws Exception {URL url = new URL(urlStr);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setRequestProperty("Content-Type", "text/json;charset=utf-8");BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));StringBuffer buf = new StringBuffer();String inputLine = in.readLine();while (inputLine != null) {buf.append(inputLine).append("\r\n");inputLine = in.readLine();}in.close();//return buf.toString().trim();}public static String httpGet2(String urlStr) throws Exception {URL url = new URL(urlStr);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));StringBuffer buf = new StringBuffer();String inputLine = in.readLine();while (inputLine != null) {buf.append(inputLine).append("\r\n");inputLine = in.readLine();}in.close();//return buf.toString().trim();}public static String httpPut(String urlStr) throws Exception {URL url = new URL(urlStr);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("PUT");conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");int code = conn.getResponseCode();BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));logger.error("code=" + conn.getResponseCode());StringBuffer buf = new StringBuffer();String inputLine = in.readLine();while (inputLine != null) {buf.append(inputLine).append("\r\n");inputLine = in.readLine();}in.close();//return (buf.toString().trim()) != null ? (buf.toString().trim()) : (code + "");}public static JSONObject httpPost(String urlStr) throws Exception {URL url = new URL(urlStr);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("POST");conn.setRequestProperty("Content-Type", "text/json;charset=utf-8");BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));StringBuffer buf = new StringBuffer();String inputLine = in.readLine();while (inputLine != null) {buf.append(inputLine).append("\r\n");inputLine = in.readLine();}in.close();//return new JSONObject(buf.toString().trim());}public static JSONObject httpPost(String urlStr, String postText) throws Exception {URL url = new URL(urlStr);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("POST");byte[] bytes = postText.getBytes("utf-8");OutputStream os = conn.getOutputStream();os.write(bytes);os.close();//BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));StringBuffer buf = new StringBuffer();String inputLine = in.readLine();while (inputLine != null) {buf.append(inputLine).append("\r\n");//inputLine = in.readLine();}in.close();//return new JSONObject(buf.toString().trim());}public static Object post(List<NameValuePair> message, String to)throws ParseException, IOException, JSONException {HttpPost post = new HttpPost(to);UrlEncodedFormEntity params = new UrlEncodedFormEntity(message, "UTF-8");post.setEntity(params);System.out.println(("[] Post \"" + message + "\" to " + post.getURI()));CloseableHttpClient client = HttpClients.createDefault();CloseableHttpResponse response = client.execute(post);int statusCode = response.getStatusLine().getStatusCode();System.out.println("[] Server Status Code: " + statusCode);String respString = null;HttpEntity entity = response.getEntity();if (entity != null) {respString = EntityUtils.toString(entity, "UTF-8");}System.out.println("[] Server return: " + respString);EntityUtils.consume(entity);JSONObject result = new JSONObject(respString.trim());if (result != null && result.has("success") && result.opt("success").equals("true")) {return result.opt("data");} else {logger.info(message);return "error";}}public static String httpPostApplication(String urlStr) throws Exception {URL url = new URL(urlStr);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("POST");conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));StringBuffer buf = new StringBuffer();String inputLine = in.readLine();while (inputLine != null) {buf.append(inputLine).append("\r\n");inputLine = in.readLine();}in.close();//return buf.toString().trim();}public static String RestfulGet(String url) {String returnString = "";try {URL restServiceURL = new URL(url);HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();httpConnection.setRequestMethod("GET");httpConnection.setRequestProperty("Accept", "application/json");httpConnection.setRequestProperty("Accept-Charset", "utf-8");httpConnection.setRequestProperty("contentType", "utf-8");if (httpConnection.getResponseCode() != 200) {throw new RuntimeException("HTTP GET Request Failed with Error code : " + httpConnection.getResponseCode());}BufferedReader responseBuffer = new BufferedReader(new InputStreamReader((httpConnection.getInputStream()), "utf-8"));String output = responseBuffer.readLine();// System.out.println("Output from Server: \n");StringBuffer buf = new StringBuffer();while (output != null) {buf.append(output).append("\r\n");output = responseBuffer.readLine();}responseBuffer.close();httpConnection.disconnect();returnString = buf.toString().trim();} catch (Exception e) {e.printStackTrace();}return returnString;}public static String RestfulPost(String url, String input) {String result = "";try {URL targetUrl = new URL(url);HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();httpConnection.setDoOutput(true);httpConnection.setRequestMethod("POST");httpConnection.setRequestProperty("Charsert", "UTF-8");httpConnection.setRequestProperty("Content-Type", "application/json");OutputStream outputStream = httpConnection.getOutputStream();outputStream.write(input.getBytes());outputStream.flush();if (httpConnection.getResponseCode() != 200) {throw new RuntimeException("Failed : HTTP error code : " + httpConnection.getResponseCode());}BufferedReader responseBuffer = new BufferedReader(new InputStreamReader((httpConnection.getInputStream()), "UTF-8"));String output;System.out.println("Output from Server:\n");StringBuffer buf = new StringBuffer();while ((output = responseBuffer.readLine()) != null) {buf.append(output).append("\r\n");}httpConnection.disconnect();responseBuffer.close();result = buf.toString().trim();} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return result;}public static org.codehaus.jettison.json.JSONObject post(net.sf.json.JSONObject json, String to)throws ParseException, IOException, JSONException {CloseableHttpClient client = HttpClients.createDefault();HttpPost post = new HttpPost(to);post.setHeader("Content-Type", "application/json");org.codehaus.jettison.json.JSONObject result = null;java.io.InputStream inStream = null;try {StringEntity s = new StringEntity(json.toString(), "utf-8");s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));post.setEntity(s);// 发送请求HttpResponse httpResponse = client.execute(post);// 获取响应输入流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();if (httpResponse.getStatusLine().getStatusCode() == 200) {result = new org.codehaus.jettison.json.JSONObject(strber.toString());} else {logger.error("请求服务端失败" + json);}} catch (Exception e) {e.printStackTrace();}return result;}public static net.sf.json.JSONObject doPutOrPost(String type, String urlString, net.sf.json.JSONObject jsonObject,String callMethed) {try {String result = "";String info = callMethed + ",调用SDK的restful接口URL:" + urlString + ",请求参数:" + jsonObject.toString() + ",请求方式:"+ type;logger.info(info);URL url = new URL(urlString);int code = 0;// 打开restful链接HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 提交模式conn.setRequestMethod(type);conn.setConnectTimeout(200000);// 连接超时 单位毫秒conn.setReadTimeout(200000);// 读取超时 单位毫秒conn.setDoOutput(true);// 是否输入参数conn.setDoInput(true);// 设置访问提交模式,表单提交conn.setRequestProperty("Content-Type", "application/json");// 设置请求头// conn.setRequestProperty(SDKKeyName, SDKKey);// conn.setRequestProperty(SDKValueName, SDKValue);// ----------------传入数据----------------------OutputStream outputStream = conn.getOutputStream();outputStream.write(jsonObject.toString().getBytes());code = conn.getResponseCode();outputStream.flush();// 判断是否创建成功logger.info(info + ",调用所得code值为:" + code);System.out.println("---------code=" + code);if (code == 200) {// 执行成功BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));StringBuffer buffer = new StringBuffer();String line = "";while ((line = reader.readLine()) != null) {buffer.append(line);}reader.close();result = buffer.toString();logger.info(info + ",调用结果信息为:" + result);net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(result);return jsonObj;} else {BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "utf-8"));StringBuffer buffer = new StringBuffer();String line = "";while ((line = reader.readLine()) != null) {buffer.append(line);}reader.close();result = buffer.toString();logger.info(info + ",调用结果信息为:" + result);net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(result);return jsonObj;}} catch (Exception e) {logger.error("请求失败", e);return null;}}public static int intOf(Object obj, int initValue) {// 1.判断参数是否合法if (obj == null || "".equals(obj)) {return initValue;} else {try {return Integer.parseInt(obj.toString());} catch (Exception e) {e.getMessage();return initValue;}}}
}

HttpUtil工具类相关推荐

  1. 拿来即用,HttpUtil工具类

    HttpUtil工具类 注意低版本有bug.https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient <!- ...

  2. 一个拿来即用的httputil工具类

    工作中难免会用httpclien进行数据的跨系统传输,这几天老在用,调别的系统的接口,今天就给大家分享出来我用的工具类吧,主要是后期我用的时候可以找到. package com.cnlive.shen ...

  3. HttpClient进行服务器传递信息,HttpUtil工具类

    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 前言 一.引入Maven依赖 二.使用步骤 1.服务器A控制层 2.服务器B控制层 前言 使用httpclient实现两个服 ...

  4. 一个简单易用的Http访问工具类for Android

    前言 去年(2017)参加服务外包省赛的时候,负责App开发的我遇到了一个小难题--Http请求.虽说已经有成熟的HttpUrlConnection库供使用,但依然感到有些不方便:进行一次简单的请求并 ...

  5. http工具类发送post和get请求

    文章目录 http协议 一.发送GET请求 二.发送POST请求 总结 http协议 HTTP是一个应用层协议,由请求和响应构成,是一个标准的客户端服务器模型.HTTP是一个无状态的协议. 提示:以下 ...

  6. java 百度api人脸识别功能(人脸识别+详细案例+接口及所需工具类)

    最近开发过程中需要用到人脸识别认证功能,然后就用的是百度API接口进行开发,起初设想用直接用人脸识别还是用注册到百度人脸库识别两种方法,为了简化开发直接就用了第一种方式: 直接上业务逻辑代码吧: po ...

  7. Hutool Http客户端工具类-HttpUtil使用

    HttpUtil是应对简单场景下Http请求的工具类封装,这个工具类可以保证在一个方法之内完成Http请求. 1 HttpUtil.get() 用于请求普通页面,然后返回页面内容的字符串,同时提供一些 ...

  8. Java工具类:HttpUtil(HttpClient实现http的请求,获取响应)

    (1)maven 依赖: <!-- HttpClinet 核心包 --> <dependency><groupId>org.apache.httpcomponent ...

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

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

  10. http工具类(支持https,连接池和失败重试)

    在实际项目中,经常会遇到调用外部(第三方)的接口,如果调用量较大的话,可能需要考虑连接池.失败重试.SSL证书等问题,以提升性能和稳定性. 以下代码是封装的小组件,供大家参考. maven依赖 < ...

最新文章

  1. 跨链Cosmos(6)ABCI 原理
  2. python inspect.stack() 的简单使用
  3. One order save debug screenshot
  4. stax 和jaxb 关系_XML解组基准:JAXB,STAx,Woodstox
  5. Base64 + 变为 空格 问题分析
  6. SQL语句中的TOP(expression) [PERCENT] [WITH TIES] 用法
  7. [导入]服务器终极安全设置与优化指南
  8. python3 开发面试题(面向对象)6.6
  9. allegro中10mil过孔_allegro阻抗隔层参考设置以及via copy操作
  10. ubuntu16.04 创建配置并使用虚拟环境
  11. DNS的作用和解析过程描述
  12. 大厂技术实现 | 腾讯信息流推荐排序中的并联双塔CTR结构 @推荐与计算广告系列
  13. Python selenium淘宝抢购物品程序
  14. Objective-c:写一份可测试的代码
  15. linux insert最后一行,insert基础用法及进阶
  16. html5分镜头脚本范例,分镜头脚本教程图解
  17. Wi-Fi Mesh协议(1)
  18. group by 用法解析
  19. 网络通信——下载管理器DownloadManager——在通知栏显示下载进度
  20. 项目 3: 创建用户分类

热门文章

  1. 【转载】C# WinForm程序中使用Unity3D控件
  2. VC第三方界面库xtremetoolkitPro使用说明
  3. JavaWeb 利用jsp 实现分页查询
  4. 配置核查保密检查等保工具箱态势感知
  5. 计算机VFP基础知识,VFP基础教程章数据库系统基础知识4
  6. 如何设计领域特定语言,实现终极业务抽象?
  7. DNF2020年全新脚本展示第一部分
  8. c语言混响,混响插件( 2cAudio Aether)
  9. php怎么发ddos包,解决服务器上通过PHP代码DDOS的方法
  10. Python语法都会,一写程序就懵,有解么?