import com.alibaba.fastjson.JSONObject; import org.apache.http.*; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.alibaba.druid.util.JdbcUtils.close; /** * @author 01375581 * @date 2018/12/18 15:11 */ public final class HttpUtil { private static Logger logger = LoggerFactory.getLogger(HttpUtil.class); /**請求編碼*/ private static final String DEFAULT_CHARSET = "UTF-8"; public String post(String url, StringEntity entity) { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = postForm(url, entity); String body = ""; body = invoke(httpClient, post); try { httpClient.close(); } catch (IOException e) { logger.error("HttpClientService post error", e); } return body; } public String post(String url, JSONObject jsonObject) { CloseableHttpClient httpClient = HttpClients.createDefault(); List<NameValuePair> parameters = new ArrayList(); for (Map.Entry<String, Object> entry : jsonObject.entrySet()) { parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString())); } HttpPost post = postForm(url, new UrlEncodedFormEntity(parameters, Charset.forName("UTF-8"))); String body = ""; body = invoke(httpClient, post); try { httpClient.close(); } catch (IOException e) { logger.error("HttpClientService post error", e); } return body; } /** * post請求 * @param url * @param param * @param requestConfig 一般需要代理的時候用 = RequestConfig.copy(RequestConfig.DEFAULT).setProxy(new HttpHost(proxyHost, Integer.valueOf(proxyPort))) .build(); * @return */ public static JSONObject httpPostWithJSON(String url, Map<String, ?> param, RequestConfig requestConfig) { JSONObject jsonObject =null; CloseableHttpClient client = null; try { if(url == null || url.trim().length() == 0){ throw new Exception("URL is null"); } HttpPost httpPost = new HttpPost(url); client = HttpClients.createDefault(); if(param != null){ StringEntity entity = new StringEntity(JSONObject.toJSONString(param), DEFAULT_CHARSET);//解決中文亂碼問題 entity.setContentEncoding(DEFAULT_CHARSET); entity.setContentType("application/json"); httpPost.setEntity(entity); } if(requestConfig!=null){ httpPost.setConfig(requestConfig); //RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT).setProxy(new HttpHost(proxyHost, Integer.valueOf(proxyPort))) .build(); //httpPost.setConfig(requestConfig); } HttpResponse resp = client.execute(httpPost); if(resp.getStatusLine().getStatusCode() == 200) { String returnStr =EntityUtils.toString(resp.getEntity(), DEFAULT_CHARSET); //System.out.println(returnStr); jsonObject = JSONObject.parseObject(returnStr.toString()); return jsonObject; } } catch (Exception e) { e.printStackTrace(); } finally { close(client); } return null; } public String postSFAPI(String url, String xml, String verifyCode) { CloseableHttpClient httpClient = HttpClients.createDefault(); List<NameValuePair> parameters = new ArrayList(); parameters.add(new BasicNameValuePair("xml", xml)); parameters.add(new BasicNameValuePair("verifyCode", verifyCode)); HttpPost post = postForm(url, new UrlEncodedFormEntity(parameters, Charset.forName("UTF-8"))); String body = ""; body = invoke(httpClient, post); try { httpClient.close(); } catch (IOException e) { logger.error("HttpClientService post error", e); } return body; } public String get(String url) { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet get = new HttpGet(url); String body = ""; body = invoke(httpClient, get); try { httpClient.close(); } catch (IOException e) { logger.error("HttpClientService get error", e); } return body; } public String delete(String url) { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpDelete delete = new HttpDelete(url); String body = ""; body = invoke(httpClient, delete); try { httpClient.close(); } catch (IOException e) { logger.error("HttpClientService get error", e); } return body; } public String invoke(CloseableHttpClient httpclient, HttpUriRequest httpost) { HttpResponse response = sendRequest(httpclient, httpost); String body = ""; int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { body = parseResponse(response); } return body; } private static String parseResponse(HttpResponse response) { HttpEntity entity = response.getEntity(); String body = ""; try { if (entity != null) { body = EntityUtils.toString(entity); } } catch (ParseException e) { logger.error("HttpClientService paseResponse error", e); } catch (IOException e) { logger.error("HttpClientService paseResponse error", e); } return body; } private static HttpResponse sendRequest(CloseableHttpClient httpclient, HttpUriRequest httpost) { HttpResponse response = null; try { response = httpclient.execute(httpost); } catch (ClientProtocolException e) { logger.error("HttpClientService sendRequest error", e); } catch (IOException e) { logger.error("HttpClientService sendRequest error", e); } return response; } public HttpPost postForm(String url, StringEntity entity) { HttpPost httpPost = new HttpPost(url); httpPost.setEntity(entity); return httpPost; } /** * 發送http POST請求 * * @param * @return 遠程響應結果 */ public static String sendPost(String u, String json) { StringBuffer sbf = new StringBuffer(); try { URL url = new URL(u); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.addRequestProperty("role", "Admin"); connection.addRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); connection.connect(); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); if (!"".equals(json)) { out.writeBytes(json); } out.flush(); out.close(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String lines; while ((lines = reader.readLine()) != null) { lines = new String(lines.getBytes(), "utf-8"); sbf.append(lines); } System.out.println(sbf); reader.close(); // 斷開連接 connection.disconnect(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sbf.toString(); } public static String doPost(String url, String json) { CloseableHttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); String result = null; try { StringEntity s = new StringEntity(json,"utf-8"); s.setContentEncoding("UTF-8"); //發送json數據需要設置contentType s.setContentType("application/json"); post.setEntity(s); HttpResponse res = client.execute(post); if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { if (res.getEntity().isStreaming() && "image/jpeg".equals(res.getEntity().getContentType().getValue())){ File file = new File("C:/Users/Administrator/Desktop/5.jpg"); if (!file.exists()){ file.createNewFile(); } OutputStream outputStream = new FileOutputStream(file); res.getEntity().writeTo(outputStream); outputStream.flush(); return "ojbk"; } // 返回json格式: result = EntityUtils.toString(res.getEntity()); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { try { client.close(); } catch (IOException e) { e.printStackTrace(); logger.error("【post關閉】 異常IOException = ", e); } } return result; } /** * * @param requestUrl 請求地址 * @param requestMethod 請求方法 * @param outputStr 參數 */ public static String httpRequest(String requestUrl,String requestMethod,String outputStr){ // 創建SSLContext StringBuffer buffer = null; try{ URL url = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(requestMethod); conn.setDoOutput(true); conn.setDoInput(true); conn.connect(); //往服務器端寫內容 if(null !=outputStr){ OutputStream os=conn.getOutputStream(); os.write(outputStr.getBytes("utf-8")); os.close(); } // 讀取服務器端返回的內容 InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); buffer = new StringBuffer(); String line = null; while ((line = br.readLine()) != null) { buffer.append(line); } br.close(); }catch(Exception e){ e.printStackTrace(); } return buffer.toString(); } public static String urlEncodeUTF8(String source){ String result=source; try { result=java.net.URLEncoder.encode(source, "UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } /** * post請求 * @param url * @param json * @return */ public static JSONObject doJsonPost(String url, String json){ CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); JSONObject response = null; try { StringEntity s = new StringEntity(json.toString()); s.setContentEncoding("UTF-8"); s.setContentType("application/json");//發送json數據需要設置contentType post.setEntity(s); HttpResponse res = httpclient.execute(post); if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ String result = EntityUtils.toString(res.getEntity());// 返回json格式: response = JSONObject.parseObject(result); } } catch (Exception e) { throw new RuntimeException(e); } return response; } /** * 發送https請求 * * @param requestUrl 請求地址 * @param requestMethod 請求方式(GET、POST) * @param outputStr 提交的數據 * @return JSONObject(通過JSONObject.get(key)的方式獲取json對象的屬性值) */ // public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) { // JSONObject jsonObject = null; // try { // // 創建SSLContext對象,並使用我們指定的信任管理器初始化 // TrustManager[] tm = { new MyX509TrustManager() }; // SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); // sslContext.init(null, tm, new SecureRandom()); // // 從上述SSLContext對象中得到SSLSocketFactory對象 // SSLSocketFactory ssf = sslContext.getSocketFactory(); // // URL url = new URL(requestUrl); // HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); // conn.setSSLSocketFactory(ssf); // // conn.setDoOutput(true); // conn.setDoInput(true); // conn.setUseCaches(false); // // // 設置請求方式(GET/POST) // conn.setRequestMethod(requestMethod); // // // 當outputStr不爲null時向輸出流寫數據 // if (null != outputStr) { // OutputStream outputStream = conn.getOutputStream(); // // 注意編碼格式 // outputStream.write(outputStr.getBytes("UTF-8")); // outputStream.close(); // } // // // 從輸入流讀取返回內容 // InputStream inputStream = conn.getInputStream(); // InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); // BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // String str = null; // StringBuffer buffer = new StringBuffer(); // while ((str = bufferedReader.readLine()) != null) { // buffer.append(str); // } // // // 釋放資源 // bufferedReader.close(); // inputStreamReader.close(); // inputStream.close(); // inputStream = null; // conn.disconnect(); // jsonObject = JSONObject.fromObject(buffer.toString()); // } catch (ConnectException ce) { // System.out.println("連接超時:{}"+ ce); // } catch (Exception e) { // System.out.println("https請求異常:{}"+ e); // } // return jsonObject; // } }
httpUtis--http發送請求 工具類
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.