假期别闲着:REST API实战演练之客户端使用Rest API

在上一篇中我们说了一下如何创建简单的rest api(假期别闲着:REST API实战演练之创建Rest API-CSDN博客),我们创建了那就是为了使用的,下面我们就看看,通过构建一个客户端程序如何使用我们创建的rest api吧。

1、新建一个java项目

Eclipse新建java项目不再赘述。

2、在新项目中引入rest api项目

因为我们在创建restapi的项目的时候没有导出jar包,可以在该项目中直接引入restapi的项目路径,如下图所示:

3、添加Org.json包

下载地址:https://central.sonatype.com/artifact/org.json/json/versions

跳转后下载org.json即可

然后把jar包添加到项目中。

4、创建一个java控制台应用程序

新建一个java项目,创建一个类,勾选复选框,带上创建静态main函数,如下所示:

5、修改代码,添加访问rest api方法

java 复制代码
package com.restful;

import java.util.Scanner;
import org.json.JSONObject;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class DataAccess {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		Scanner scanner = new Scanner(System.in);
		
		System.out.println("Welcome to the Person Info Command Line Editor.");
		System.out.println("(PICLER for short.)");
		System.out.println("Do you want to get or set a person's info?");
		System.out.println("(Type 'get' or 'set' now.)");
		String getOrSet = scanner.nextLine();
		if("get".equalsIgnoreCase(getOrSet)){
			System.out.println("Whose info do you want to get?");
			System.out.println("(Type a person's name now.)");
			String name = scanner.nextLine();
			
			String jsonString = getPersonData(name);
			JSONObject jsonObject = new JSONObject(jsonString);
 
			int birthYear = jsonObject.getInt("birthYear");
			System.out.println(name + " was born in " + birthYear + ".");
			
			String about = jsonObject.getString("about");
			System.out.println(about);
		}
		else if("set".equalsIgnoreCase(getOrSet)){
			System.out.println("Whose info do you want to set?");
			System.out.println("(Type a person's name now.)");
			String name = scanner.nextLine();
			
			System.out.println("When was " + name + " born?");
			System.out.println("(Type a year now.)");
			String birthYear = scanner.nextLine();
			
			System.out.println("Can you tell me about " + name + "?");
			System.out.println("(Type a sentence now.)");
			String about = scanner.nextLine();
			
			setPersonData(name, birthYear, about);
		}
		
		scanner.close();
		
		System.out.println("Thanks for using PICLER.");
	}
	public static String getPersonData(String name) throws IOException{
		 
		HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:8080/HelloJSP/people/" + name).openConnection();
		
		connection.setRequestMethod("GET");
 
		int responseCode = connection.getResponseCode();
		if(responseCode == 200){
			String response = "";
			Scanner scanner = new Scanner(connection.getInputStream());
			while(scanner.hasNextLine()){
				response += scanner.nextLine();
				response += "\n";
			}
			scanner.close();
 
			return response;
		}
		
		// an error happened
		return null;
	}
 
	@SuppressWarnings("deprecation")
	public static void setPersonData(String name, String birthYear, String about) throws IOException{
		HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:8080/HelloJSP/people/" + name).openConnection();
 
		connection.setRequestMethod("POST");
		
		String postData = "name=" + URLEncoder.encode(name);
		postData += "&about=" + URLEncoder.encode(about);
		postData += "&birthYear=" + birthYear;
		
		connection.setDoOutput(true);
	    OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
	    wr.write(postData);
	    wr.flush();
		
		int responseCode = connection.getResponseCode();
		if(responseCode == 200){
			System.out.println("POST was successful.");
		}
		else if(responseCode == 401){
			System.out.println("Wrong password.");
		}
	}
}

6、运行测试

我们写的是一个java控制台应用程序,那么直接运行后在控制台输入信息即可。

运行后,根据提示输入(测试前确保前面的创建rest api是启动着的):

输入se测试如下:

通过客户端修改后,我们再在浏览器看一下我们修改的数据。

参考资料:

假期别闲着:REST API实战演练之创建Rest API-CSDN博客

https://blog.csdn.net/allway2/article/details/123375541

相关推荐
为何创造硅基生物3 小时前
C语言 结构体内存对齐规则(通俗易懂版)
c语言·开发语言
吃好睡好便好3 小时前
在Matlab中绘制横直方图
开发语言·学习·算法·matlab
星寂樱易李3 小时前
iperf3 + Python-- 网络带宽、网速、网络稳定性
开发语言·网络·python
仰泳之鹅3 小时前
【C语言】自定义数据类型2——联合体与枚举
c语言·开发语言·算法
之歆4 小时前
DAY_12JavaScript DOM 完全指南(二):实战与性能篇
开发语言·前端·javascript·ecmascript
cen__y5 小时前
Linux12(Git01)
linux·运维·服务器·c语言·开发语言·git
AI人工智能+电脑小能手5 小时前
【大白话说Java面试题 第65题】【JVM篇】第25题:谈谈对 OOM 的认识
java·开发语言·jvm
社交怪人5 小时前
【算平均分】信息学奥赛一本通C语言解法(题号2071)
c语言·开发语言
郭涤生6 小时前
不同主机之间网络通信-以太网连接复习
开发语言·rk3588
山居秋暝LS6 小时前
【无标题】RTX00安装paddle OCR,win11不能装最新的,也不能用GPU
开发语言·r语言