import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; 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 javax.net.ssl.*; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; /** * 第三方链接请求工具 */ public class HttpClientUtil { /** * 使用httpclint 发送请求 * * @param url 调用的连接 * @param parms 使用map装入需要调用的参数名与值 * @return 响应结果 */ public static JSONObject doPostForm(String url, Map<String, String> parms) { HttpPost httpPost = new HttpPost(url); ArrayList<BasicNameValuePair> list = new ArrayList<>(); parms.forEach((key, value) -> list.add(new BasicNameValuePair(key, value))); CloseableHttpClient httpClient = HttpClients.createDefault(); try { if (Objects.nonNull(parms) && parms.size() > 0) { httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8")); } HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(entity, "UTF-8")); return jsonObject; } catch (IOException e) { e.printStackTrace(); } finally { if (Objects.nonNull(httpClient)) { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } public static JSONObject doPutForm(String url, Map<String, String> parms) throws Exception { HttpPut httpPut = new HttpPut(url); ArrayList<BasicNameValuePair> list = new ArrayList<>(); parms.forEach((key, value) -> list.add(new BasicNameValuePair(key, value))); CloseableHttpClient httpClient = HttpClients.createDefault(); try { if (Objects.nonNull(parms) && parms.size() > 0) { httpPut.setEntity(new UrlEncodedFormEntity(list, "UTF-8")); } InputStream content = httpPut.getEntity().getContent(); InputStreamReader inputStreamReader = new InputStreamReader(content, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String readLine = bufferedReader.readLine(); String s = URLDecoder.decode(readLine, "UTF-8"); HttpResponse response = httpClient.execute(httpPut); HttpEntity entity = response.getEntity(); JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(entity, "UTF-8")); return jsonObject; } catch (IOException e) { e.printStackTrace(); } finally { if (Objects.nonNull(httpClient)) { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } public static JSONObject doGetForm(String url, Map<String, String> parms) throws Exception { ArrayList<BasicNameValuePair> list = new ArrayList<>(); parms.forEach((key, value) -> list.add(new BasicNameValuePair(key, value))); CloseableHttpClient httpClient = HttpClients.createDefault(); try { //3、转化参数 String params = EntityUtils.toString(new UrlEncodedFormEntity(list, Consts.UTF_8)); //4、创建HttpGet请求 HttpGet httpGet = new HttpGet(url + "?" + params); CloseableHttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(entity, "UTF-8")); return jsonObject; } catch (IOException e) { e.printStackTrace(); } finally { if (Objects.nonNull(httpClient)) { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } /** * 发送HttpPost请求,参数为map * * @param url * @param map * @return */ public static String sendPost(String url, Map<String, String> map) { CloseableHttpClient httpclient = HttpClients.createDefault(); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : map.entrySet()) { //给参数赋值 formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8); HttpPost httppost = new HttpPost(url); httppost.setEntity(entity); CloseableHttpResponse response = null; System.out.println(map); try { response = httpclient.execute(httppost); } catch (IOException e) { e.printStackTrace(); } HttpEntity entity1 = response.getEntity(); String result = ""; try { InputStream content = entity1.getContent(); BufferedReader in = null; in = new BufferedReader( new InputStreamReader(content, "UTF-8")); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { e.printStackTrace(); } return result; } /** * 向指定 URL 发送POST方法的请求 * * @param url 发送请求的 URL * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return 所代表远程资源的响应结果 */ public static String sendPost(String url, String param, Map<String, String> header) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = null; if ("https".equals(realUrl.getProtocol())) { SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[]{tm}, null); HttpsURLConnection connHttps = (HttpsURLConnection) realUrl.openConnection(); connHttps.setSSLSocketFactory(ctx.getSocketFactory()); connHttps.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true;//默认认证不通过,进行证书校验。 } }); conn = connHttps; } else { conn = (HttpURLConnection) realUrl.openConnection(); } // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); for (Map.Entry<String, String> entry : header.entrySet()) { conn.setRequestProperty(entry.getKey(), entry.getValue()); } // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 out = new PrintWriter(conn.getOutputStream()); // 发送请求参数 out.print(param); // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送 POST 请求出现异常!" + e); e.printStackTrace(); } //使用finally块来关闭输出流、输入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } }
简单的示例:
public static void main(String[] args) { //第三方URL String apiUrl = ""; Map<String, String> header = new HashMap<>(); header.put("token", "token"); StringBuffer params = new StringBuffer(); params.append("app_key=").append("app_key").append("&"); params.append("keyword=").append("keyword").append("&"); String str = HttpClientUtil.sendPost(apiUrl, params.toString(), header); return str; }
标签:Java,String,第三方,return,import,apache,new,null,链接 From: https://www.cnblogs.com/springclout/p/17861220.html