package com.hxjt.dataupload.utils; import com.alibaba.fastjson.JSONObject; import org.apache.http.ParseException; import org.apache.http.client.ResponseHandler; 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.BasicResponseHandler; 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.tomcat.util.http.fileupload.ByteArrayOutputStream; import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * 工具类,用于发送get,post请求 */ public class HttpUtils { public static String doGet(String httpurl) { HttpURLConnection connection = null; InputStream is = null; BufferedReader br = null; String result = null;// 返回结果字符串 try { // 创建远程url连接对象 URL url = new URL(httpurl); // 通过远程url连接对象打开一个连接,强转成httpURLConnection类 connection = (HttpURLConnection) url.openConnection(); // 设置连接方式:get connection.setRequestMethod("GET"); // 设置连接主机服务器的超时时间:15000毫秒 connection.setConnectTimeout(15000); // 设置读取远程返回的数据时间:60000毫秒 connection.setReadTimeout(60000); // 发送请求 connection.connect(); // 通过connection连接,获取输入流 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 封装输入流is,并指定字符集 br = new BufferedReader(new InputStreamReader(is, "UTF-8")); // 存放数据 StringBuffer sbf = new StringBuffer(); String temp = null; while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭资源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } connection.disconnect();// 关闭远程连接 } return result; } public static String doPost(String url, String param) { String result = ""; DataOutputStream dataOutputStreamSend = null; InputStream inputStream = null; ByteArrayOutputStream dataOutputStream = null; try { URL httpUrl = new URL(url); HttpURLConnection urlConnection = (HttpURLConnection)httpUrl.openConnection(); // 设置超时时间 urlConnection.setConnectTimeout(10000); urlConnection.setReadTimeout(30000); urlConnection.setRequestMethod("POST"); // 设置通用请求类型 urlConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); urlConnection.setRequestProperty("Charset", "UTF-8"); // 设置链接状态 urlConnection.setRequestProperty("connection", "keep-alive"); // post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false; urlConnection.setDoOutput(true); // 设置是否从httpUrlConnection读入,默认情况下是true; urlConnection.setDoInput(true); // Post 请求不能使用缓存 urlConnection.setUseCaches(false); // 设置本次连接是否自动处理重定向 urlConnection.setInstanceFollowRedirects(true); urlConnection.connect(); // ++++++++++++++++++++++++++++++++++ // TODO 写入参数 dataOutputStreamSend = new DataOutputStream(urlConnection.getOutputStream()); dataOutputStreamSend.write(param.getBytes()); dataOutputStreamSend.flush(); // +++++++++++++++++++++++++++++++ if (urlConnection.getResponseCode() == 200) { // 获取返回流 result = getResult(urlConnection.getInputStream()); } } catch (IOException e) { // url格式错误 e.printStackTrace(); } return result; } private static String getResult(InputStream inputStream) { String result = ""; ByteArrayOutputStream dataOutputStream = null; try { byte[] buf = new byte[1024]; int n; dataOutputStream = new ByteArrayOutputStream(); while (((n = inputStream.read(buf)) != -1)) { dataOutputStream.write(buf, 0, n); } dataOutputStream.toByteArray(); result = new String(dataOutputStream.toByteArray(), "UTF-8"); } catch (IOException e) { e.printStackTrace(); } return result; } /** * post 发送数据 */ public static String sendPost(String message,String url) { String response = ""; CloseableHttpClient httpClient = HttpClients.createDefault(); ResponseHandler responseHandler = new BasicResponseHandler(); try { // API地址 httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); // 构建消息实体 StringEntity requestEntity = new StringEntity(message, "utf-8"); requestEntity.setContentEncoding("UTF-8"); // 构造消息头 // 发送Json格式的数据请求 httpPost.setHeader("Content-type", "application/json"); httpPost.setEntity(requestEntity); //发送post请求获取响应值 String returnValue = httpClient.execute(httpPost, responseHandler); if (returnValue != null) { response = returnValue; } } catch (Exception e) { System.err.println(e); } finally { try { httpClient.close(); } catch (IOException e) { // TODO Auto-generated catch block System.err.println(e); } } return response; } /** * 发送post请求 * @param url 路径 * @param jsonObject 参数(json类型) * @param encoding 编码格式 * @return * @throws ParseException * @throws IOException */ public static String send(String url, JSONObject jsonObject, String encoding, String userKey, String userToken) throws ParseException, IOException{ String body = ""; //创建httpclient对象 CloseableHttpClient client = HttpClients.createDefault(); //创建post方式请求对象 HttpPost httpPost = new HttpPost(url); //装填参数 StringEntity s = new StringEntity(jsonObject.toString(), "utf-8"); s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); //设置参数到请求对象中 httpPost.setEntity(s); // System.out.println("请求参数:"+nvps.toString()); //设置header信息 //指定报文头【Content-type】、【User-Agent】 httpPost.setHeader("Content-type", "application/json"); httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); httpPost.setHeader("user-token",userToken); httpPost.setHeader("user-key",userKey); System.out.println("请求地址:"+url); System.out.println("请求Key:"+userKey); System.out.println("请求token:"+userToken); //执行请求操作,并拿到结果(同步阻塞) CloseableHttpResponse response = client.execute(httpPost); //获取结果实体 org.apache.http.HttpEntity entity = response.getEntity(); if (entity != null) { //按指定编码转换结果实体为String类型 body = EntityUtils.toString(entity, encoding); } EntityUtils.consume(entity); //释放链接 response.close(); return body; } }