package com.example.jz.utils; import org.apache.http.*; 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.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class HttpUtil { private static final CloseableHttpClient httpclient = HttpClients.createDefault(); public static String doGet(String urlPath, Map params) throws Exception { StringBuilder sb = new StringBuilder(urlPath); if (params != null && !params.isEmpty()) { // 说明有参数 sb.append("?"); Set> set = params.entrySet(); for (Entry entry : set) { // 遍历map里面的参数 String key = entry.getKey(); String value = ""; if (null != entry.getValue()) { value = entry.getValue().toString(); // 转码 value = URLEncoder.encode(value, "UTF-8"); } sb.append(key).append("=").append(value).append("&"); } sb.deleteCharAt(sb.length() - 1); // 删除最后一个& } // System.out.println(sb.toString()); URL url = new URL(sb.toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); // 5s超时 conn.setRequestMethod("GET"); if (conn.getResponseCode() == HttpStatus.SC_OK) {// HttpStatus.SC_OK == // 200 BufferedReader reader = new BufferedReader(new InputStreamReader( conn.getInputStream())); StringBuilder sbs = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sbs.append(line); } // JSONObject jsonObject = new JSONObject(sbs.toString()); return sbs.toString(); } return null; } /** * 发送HttpPost请求,参数为map * @param url * @param map * @return */ public static String sendPost(String url, Map map) { List formparams = new ArrayList(); for (Entry entry : map.entrySet()) { formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString())); } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8); HttpPost httppost = new HttpPost(url); httppost.setEntity(entity); CloseableHttpResponse response = null; try { response = httpclient.execute(httppost); } catch (IOException e) { e.printStackTrace(); } HttpEntity entity1 = response.getEntity(); String result = null; try { result = EntityUtils.toString(entity1); } catch (ParseException | IOException e) { e.printStackTrace(); } return result; } }