Java REST Client
Posted Life Overflow
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java REST Client相关的知识,希望对你有一定的参考价值。
GET:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class GETRestClient { private static final String targetURL = "http://localhost:8080/path/get.serv"; public static void main(String[] args) { try { URL restServiceURL = new URL(targetURL); HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection(); httpConnection.setRequestMethod("GET"); httpConnection.setRequestProperty("Accept", "application/json"); if (httpConnection.getResponseCode() != 200) { throw new RuntimeException("HTTP GET Request Failed with Error code : "+ httpConnection.getResponseCode()); } BufferedReader responseBuffer = new BufferedReader( new InputStreamReader((httpConnection.getInputStream()))); String output; System.out.println("Output from Server: \n"); while ((output = responseBuffer.readLine()) != null) { System.out.println(output); } httpConnection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
POST:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class POSTRestClient { private static final String targetURL = "http://localhost:8080/path/post.serv"; public static void main(String[] args) { try { URL targetUrl = new URL(targetURL); HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection(); httpConnection.setDoOutput(true); httpConnection.setRequestMethod("POST"); httpConnection.setRequestProperty("Content-Type", "application/json"); String input = "{\"id\":1,\"no\":\"no0003\",\"name\":\"jack\"}"; OutputStream outputStream = httpConnection.getOutputStream(); outputStream.write(input.getBytes()); outputStream.flush(); if (httpConnection.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + httpConnection.getResponseCode()); } BufferedReader responseBuffer = new BufferedReader( new InputStreamReader((httpConnection.getInputStream()))); String output; System.out.println("Output from Server:\n"); while ((output = responseBuffer.readLine()) != null) { System.out.println(output); } httpConnection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
以上是关于Java REST Client的主要内容,如果未能解决你的问题,请参考以下文章
商城项目19_elasticsearch-Rest-Client整合SpringBoot中使用保存数据利用JAVA代码操作es
ElasticSearch04_elasticsearch-Rest-Client整合SpringBoot中使用保存数据利用JAVA代码操作es
商城项目19_elasticsearch-Rest-Client整合SpringBoot中使用保存数据利用JAVA代码操作es
elasticsearch系列七:ES Java客户端-Elasticsearch Java client(ES Client 简介Java REST ClientJava ClientSpri(代码