假期别闲着: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

相关推荐
编程零零七2 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
2401_858286113 小时前
52.【C语言】 字符函数和字符串函数(strcat函数)
c语言·开发语言
铁松溜达py3 小时前
编译器/工具链环境:GCC vs LLVM/Clang,MSVCRT vs UCRT
开发语言·网络
everyStudy3 小时前
JavaScript如何判断输入的是空格
开发语言·javascript·ecmascript
C-SDN花园GGbond4 小时前
【探索数据结构与算法】插入排序:原理、实现与分析(图文详解)
c语言·开发语言·数据结构·排序算法
迷迭所归处5 小时前
C++ —— 关于vector
开发语言·c++·算法
架构文摘JGWZ6 小时前
Java 23 的12 个新特性!!
java·开发语言·学习
leon6256 小时前
优化算法(一)—遗传算法(Genetic Algorithm)附MATLAB程序
开发语言·算法·matlab
锦亦之22337 小时前
QT+OSG+OSG-earth如何在窗口显示一个地球
开发语言·qt
我是苏苏7 小时前
Web开发:ABP框架2——入门级别的增删改查Demo
java·开发语言