HTTPUtils.java 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. package com.chinaitop.depot.utils;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.net.URI;
  6. import java.nio.charset.Charset;
  7. import java.text.SimpleDateFormat;
  8. import java.util.ArrayList;
  9. import java.util.Date;
  10. import java.util.Iterator;
  11. import java.util.List;
  12. import java.util.Map;
  13. import java.util.Random;
  14. import org.apache.http.HttpEntity;
  15. import org.apache.http.HttpResponse;
  16. import org.apache.http.HttpStatus;
  17. import org.apache.http.NameValuePair;
  18. import org.apache.http.StatusLine;
  19. import org.apache.http.client.HttpClient;
  20. import org.apache.http.client.entity.UrlEncodedFormEntity;
  21. import org.apache.http.client.methods.CloseableHttpResponse;
  22. import org.apache.http.client.methods.HttpGet;
  23. import org.apache.http.client.methods.HttpPost;
  24. import org.apache.http.entity.ContentType;
  25. import org.apache.http.entity.StringEntity;
  26. //import org.apache.http.entity.mime.MultipartEntityBuilder;
  27. import org.apache.http.impl.client.CloseableHttpClient;
  28. import org.apache.http.impl.client.DefaultHttpClient;
  29. import org.apache.http.impl.client.HttpClients;
  30. import org.apache.http.message.BasicNameValuePair;
  31. import org.apache.http.protocol.HTTP;
  32. import org.apache.http.util.EntityUtils;
  33. import org.apache.log4j.LogManager;
  34. import org.apache.log4j.Logger;
  35. import org.springframework.web.multipart.MultipartFile;
  36. public class HTTPUtils {
  37. private final static Logger logger = LogManager.getLogger(HTTPUtils.class);
  38. /**
  39. * get请求
  40. * @return
  41. */
  42. public static String doGet(String url) {
  43. try {
  44. HttpClient client = new DefaultHttpClient();
  45. //发送get请求
  46. HttpGet request = new HttpGet(url);
  47. HttpResponse response = client.execute(request);
  48. /**请求发送成功,并得到响应**/
  49. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  50. /**读取服务器返回过来的json字符串数据**/
  51. String strResult = EntityUtils.toString(response.getEntity());
  52. return strResult;
  53. }
  54. }
  55. catch (IOException e) {
  56. e.printStackTrace();
  57. }
  58. return null;
  59. }
  60. /**
  61. * post请求(用于key-value格式的参数)
  62. * @param url
  63. * @param params
  64. * @return
  65. */
  66. public static String doPost(String url, Map params){
  67. BufferedReader in = null;
  68. try {
  69. // 定义HttpClient
  70. HttpClient client = new DefaultHttpClient();
  71. // 实例化HTTP方法
  72. HttpPost request = new HttpPost();
  73. request.setURI(new URI(url));
  74. //设置参数
  75. List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  76. for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
  77. String name = (String) iter.next();
  78. String value = String.valueOf(params.get(name));
  79. nvps.add(new BasicNameValuePair(name, value));
  80. //System.out.println(name +"-"+value);
  81. }
  82. request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
  83. HttpResponse response = client.execute(request);
  84. int code = response.getStatusLine().getStatusCode();
  85. if(code == 200){ //请求成功
  86. in = new BufferedReader(new InputStreamReader(response.getEntity()
  87. .getContent(),"utf-8"));
  88. StringBuffer sb = new StringBuffer("");
  89. String line = "";
  90. String NL = System.getProperty("line.separator");
  91. while ((line = in.readLine()) != null) {
  92. sb.append(line + NL);
  93. }
  94. in.close();
  95. return sb.toString();
  96. } else{ //
  97. String ztm = "状态码:" + code;
  98. System.out.println("状态码:" + code);
  99. return ztm;
  100. }
  101. }
  102. catch(Exception e){
  103. e.printStackTrace();
  104. return null;
  105. }
  106. }
  107. /**
  108. * post请求(用于请求json格式的参数)
  109. * @param url
  110. * @param params
  111. * @return
  112. */
  113. public static String doPost(String url, String params) throws Exception {
  114. CloseableHttpClient httpclient = HttpClients.createDefault();
  115. HttpPost httpPost = new HttpPost(url);// 创建httpPost
  116. httpPost.setHeader("Accept", "application/json");
  117. httpPost.setHeader("Content-Type", "application/json");
  118. String charSet = "UTF-8";
  119. StringEntity entity = new StringEntity(params, charSet);
  120. httpPost.setEntity(entity);
  121. CloseableHttpResponse response = null;
  122. try {
  123. response = httpclient.execute(httpPost);
  124. StatusLine status = response.getStatusLine();
  125. int state = status.getStatusCode();
  126. if (state == HttpStatus.SC_OK) {
  127. HttpEntity responseEntity = response.getEntity();
  128. String jsonString = EntityUtils.toString(responseEntity);
  129. return jsonString;
  130. }
  131. else{
  132. logger.error("请求返回:"+state+"("+url+")");
  133. }
  134. }
  135. finally {
  136. if (response != null) {
  137. try {
  138. response.close();
  139. } catch (IOException e) {
  140. e.printStackTrace();
  141. }
  142. }
  143. try {
  144. httpclient.close();
  145. } catch (IOException e) {
  146. e.printStackTrace();
  147. }
  148. }
  149. return null;
  150. }
  151. /**
  152. * 中转文件
  153. *
  154. * @param file
  155. * 上传的文件
  156. * @return 响应结果
  157. */
  158. /*public static String httpClientUploadFile(MultipartFile file,String remoteurl) {
  159. System.out.println("上传");
  160. System.out.println("上传参数"+file);
  161. System.out.println("上传参数"+remoteurl);
  162. if(file.isEmpty()){
  163. return null;
  164. }
  165. String remote_url=remoteurl;
  166. CloseableHttpClient httpClient = HttpClients.createDefault();
  167. String result = "";
  168. try {
  169. String fileName = file.getOriginalFilename();
  170. Integer start = fileName.lastIndexOf(".");
  171. Integer length = fileName.length();
  172. String finalType = fileName.substring(start, length);
  173. SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
  174. fileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + finalType;
  175. HttpPost httpPost = new HttpPost(remote_url);
  176. MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  177. builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
  178. builder.addTextBody("filename", fileName);// 类似浏览器表单提交,对应input的name和value
  179. HttpEntity entity = builder.build();
  180. httpPost.setEntity(entity);
  181. HttpResponse response = httpClient.execute(httpPost);// 执行提交
  182. HttpEntity responseEntity = response.getEntity();
  183. if (responseEntity != null) {
  184. // 将响应内容转换为字符串
  185. result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
  186. }
  187. } catch (IOException e) {
  188. e.printStackTrace();
  189. } catch (Exception e) {
  190. e.printStackTrace();
  191. } finally {
  192. try {
  193. httpClient.close();
  194. } catch (IOException e) {
  195. e.printStackTrace();
  196. }
  197. }
  198. return result;
  199. }*/
  200. // public static void main(String[] args) throws Exception {
  201. // JSONObject json = new JSONObject();
  202. // json.put("action", "test");
  203. // URL url = new URL("http://localhost:8890/fileUpload/tt");
  204. // String resp = post(url, json.toString());
  205. // System.out.println(resp);
  206. // }
  207. }