/** * 发送HttpGet请求 * * @param url * 请求地址 * @return 返回字符串 */ public static String sendGet(String url) { String result = null; CloseableHttpResponse response = null; try { HttpGet httpGet = new HttpGet(url); httpGet.setHeader("User-Agent", userAgent); // 设置4s超时 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(4000) .setConnectTimeout(4000).build();// 设置请求和传输超时时间 httpGet.setConfig(requestConfig); response = httpclient.execute(httpGet); HttpEntity entity = response.getEntity(); if (entity != null) { result = EntityUtils.toString(entity); } } catch (Exception e) { log.info("处理失败 {}" + e); } finally { if (response != null) { try { EntityUtils.consume(response.getEntity()); } catch (Exception e) { log.info(e.getMessage()); } } } return result; }
/** * * 发送HttpPost请求,参数为map * * @param url * 请求地址 * @param map * 请求参数 * @return * 返回字符串 */ public static String sendPost(String url, Map<String, String> map) { // 设置参数 List<NameValuePair> formparams = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : map.entrySet()) { formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } // 编码 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8); // 取得HttpPost对象 HttpPost httpPost = new HttpPost(url); // 防止被当成攻击添加的 httpPost.setHeader("User-Agent", userAgent); // 设置4s超时 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(4000) .setConnectTimeout(4000).build();// 设置请求和传输超时时间 httpPost.setConfig(requestConfig); // 参数放入Entity httpPost.setEntity(formEntity); CloseableHttpResponse response = null; String result = null; try { // 执行post请求 response = httpclient.execute(httpPost); // 得到entity HttpEntity entity = response.getEntity(); // 得到字符串 result = EntityUtils.toString(entity); } catch (Exception e) { log.info(e.getMessage()); } finally { if (response != null) { try { EntityUtils.consume(response.getEntity()); } catch (Exception e) { log.info(e.getMessage()); } } } return result; }