Java 구현 가져오기, PUT, POST, 요청 삭제:
1, 가져오기
public static String doGet(String strUrl ){ String strReturn=""; HttpGet httpGet = new HttpGet(strUrl); CloseableHttpClient httpclient = null; CloseableHttpResponse response1=null; try { httpclient = HttpClients.createDefault(); response1 = httpclient.execute(httpGet); HttpEntity entity1 = response1.getEntity(); strReturn=EntityUtils.toString(entity1) ; EntityUtils.consume(entity1); }catch(Exception e){ e.printStackTrace(); }finally { try { if(response1!=null) response1.close(); } catch (IOException e) { e.printStackTrace(); } } return strReturn; }
2, Put 가져오기
public static String doPut(String strUrl,String param){ CloseableHttpClient httpclient = HttpClients.createDefault(); StringBuffer jsonString= new StringBuffer(); try { final HttpPut put=new HttpPut(strUrl); put.setEntity(new StringEntity(param,"UTF-8")); CloseableHttpResponse response1= httpclient.execute(put ); try { HttpEntity entity1 = response1.getEntity(); BufferedReader br = new BufferedReader(new InputStreamReader(entity1.getContent())); String line; while ((line = br.readLine()) != null) { jsonString.append(line); } EntityUtils.consume(entity1); } finally { response1.close(); } }catch(Exception e){ e.printStackTrace(); } return jsonString.toString(); }
3, 게시
public static String doPost(String requestUrl, String payload) { String strReturn=""; PostMethod httpost = new PostMethod(requestUrl); httpost.setRequestBody(payload); try { httpClient.executeMethod(httpost); byte[] bytes = httpost.getResponseBody(); strReturn= new String(bytes) ; } catch (Exception e) { e.printStackTrace(); } return strReturn; }
4,
public static void doDelete(String urlToRead) throws Exception { URL url = new URL(urlToRead); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" ); httpCon.setRequestMethod("DELETE"); httpCon.connect(); httpCon.disconnect(); }
이상 삭제 Java, PUT, POST 구현이며, 요청한 내용을 삭제합니다. 자세한 관련 내용은 PHP 중국어 홈페이지(www.php.cn)를 참고해주세요!
관련 기사:
Java 프로그래밍의 일반적인 문제 요약에 대한 자세한 소개