HttpClient發送Post請求,get請求
阿新 • • 發佈:2017-10-12
人的 new ole 大神 put blog cli 請求 pre
// 創建默認的httpclient實例 CloseableHttpClient httpclient = getHttpClient(); CloseableHttpResponse response = null; // 創建httpPost HttpPost httpPost = new HttpPost("url地址");
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json; charset=utf-8"); try { StringEntity param= new StringEntity(params, ContentType.APPLICATION_JSON); httpPost.setEntity(param); response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); if(entity != null){ InputStream is = entity.getContent();} } catch (Exception e) { LOG.error("sendPostRequest error:", e); } finally { try { //關閉連接,釋放資源 response.close(); httpclient.close(); } catch (Exception e) { LOG.error("HttpClient close error:", e); } }
發送Get請求
CloseableHttpClient httpclient = getHttpClient(); CloseableHttpResponse response = null; HttpGet httpget = new HttpGet("url地址"); try { response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if(entity != null){ InputStream is = entity.getContent(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { //關閉連接,釋放資源 response.close(); closeHttpClient(httpclient); } catch (Exception e) { LOG.error("HttpClient close error:", e); } }
借用某位大神的代碼,只為日後方便查閱,請勿介意。
讀書人的事情怎麽能叫偷,那叫竊!
HttpClient發送Post請求,get請求