public class HttpHelper { private int count=1; //get请求 public static String doGet(String url) { try { HttpClient client = HttpClients.createDefault(); HttpGet request = new HttpGet(url); //发送get请求 HttpResponse response = client.execute(request); /**请求发送成功,并得到响应**/ if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { /**读取服务器返回过来的json字符串数据**/ String strResult = EntityUtils.toString(response.getEntity()); return strResult; } } catch (IOException e) { e.printStackTrace(); } return null; } //post请求(用于key-value格式的参数) public static String doPost(String url, Map params) { BufferedReader in = null; try { HttpClient client = HttpClients.createDefault(); // 定义HttpClient HttpPost request = new HttpPost();// 实例化HTTP方法 request.setURI(new URI(url)); List<NameValuePair> nvps = new ArrayList<NameValuePair>();//设置参数 for (Iterator iter = params.keySet().iterator(); iter.hasNext(); ) { String name = (String) iter.next(); String value = String.valueOf(params.get(name)); nvps.add(new BasicNameValuePair(name, value)); } request.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); HttpResponse response = client.execute(request); int code = response.getStatusLine().getStatusCode(); if (code == 200) { //请求成功 in = new BufferedReader(new InputStreamReader(response.getEntity() .getContent(), "utf-8")); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); return sb.toString(); } else { System.out.println("状态码:" + code); return null; } } catch (Exception e) { e.printStackTrace(); return null; } } //post请求(用于请求json格式的参数) public String doPost(String url, String params) throws Exception { //CloseableHttpClient httpclient = HttpClients.createDefault();//设置默认httpclient count++; HttpPost httpPost = new HttpPost(url);// 创建httpPost httpPost.setHeader("Content-Type", "application/json"); httpPost.setHeader("Authorization", "3fd498f1-9030-");//请求验证 StringEntity entity = new StringEntity(params, FinalCode.CHARSET); httpPost.setEntity(entity); CloseableHttpResponse response = null; try { response = HttpUtil.getInstance().getHttpClient().execute(httpPost); StatusLine status = response.getStatusLine(); int state = status.getStatusCode(); if (state == HttpStatus.SC_OK) { HttpEntity responseEntity = response.getEntity(); String jsonString = EntityUtils.toString(responseEntity); return jsonString; } else { //logger.error("请求返回:"+state+"("+url+")"); } } catch (Exception e) { e.printStackTrace(); System.out.println(Thread.currentThread().getId()+"------------111111111111111111111111111"); Thread.sleep(3000); if(count<=3) doPost(url,params); }finally { if (response != null) { // try { // response.close(); // } catch (IOException e) { // e.printStackTrace(); // } } //暂时不需要关闭请求连接池 // try { // httpClient.close(); // } catch (IOException e) { // e.printStackTrace(); // } } return null; } }
很多超时重发的资料都没有直接从catch里捕获好用。