如何在Java客户端调用RESTful服务
在这个例子中,我们将看到如何使用java.net包实用工具,创建一个访问REST服务RESTful的客户端。当然这不是创建一个RESTful客户端最简单的方法,因为你必须自己读取服务器端的响应,以及Json和Java对象的转换。
请求Get
public class JavaNetURLRESTFulClient {
private static final String targetURL = "http://localhost:8080/JerseyJSONExample/rest/jsonServices/print/Jamie";
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();
}
} }
运行后输出结果是:
Output from Server: {"id":1,"firstName":"Jamie","age":22,"lastName":"Diaz"}
POST提交:
public class JavaNetURLRESTFulClient {
private static final String targetURL = "http://localhost:8080/JerseyJSONExample/rest/jsonServices/send";
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,\"firstName\":\"Liam\",\"age\":22,\"lastName\":\"Marco\"}";
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 Random类、ThreadLocalRandom类
- Java if判断对象为null时,null放在比较运算符的左边还是右边?哪种才是java标准?进来看看你就知道了
- Java RESTful Web Service实战(第2版) 1.9 本章小结
- Java 8 Default Methods Explained in 5 minutes
- Java垃圾回收(GC)机制详解
- Error:java: Compilation failed: internal java compiler error 解决办法
- 【Java】整理关于java的String类,equals函数和比较操作符的区别
- 【Java】WSDL 简介
- 基于Java实现(Web)考勤管理系统【100010040】
- Java IDEA中设置导入import java.xx.*和设置导入具体的import java.xx.yy;
- Java base64 添加data URI
- flink error: Exception in thread "main" java.lang.NoClassDefFoundError
- Java打印输出:java在线8x8x
- Android Reports comments that contain Java code. Usually code that is commented out
- Java_解决java.security.cert.CertificateException: Certificates does not conform to algorithm constraints
- 浅析Java对集合进行操作时报java.util.ConcurrentModificationException并发修改异常问题:产生原因、单线程/多线程环境解决、CopyOnWriteArrayList线程安全的ArrayList、fail-fast快速失败机制防止多线程修改集合造成并发问题
- 【JAVA】归并排序
- Java 加号变乘号
- 【JDBC】java PreparedStatement操作oracle数据库
- 一看就会的FTP文件服务器操作,Java,全!
- Java小白入门200例18之随机数的使用
- 【Java笔记】配置文件java.util.Properties类的使用
- 多种方式解决Java控制台报错 java.util.LinkedHashMap cannot be cast to.....
- 解决Java使用response下载文件报错,并总结可能出错的原因: java.io.IOException: 你的主机中的软件中止了一个已建立的连接。
- java 字符串输出到文件