假期别闲着: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 分钟前
40 C++ STL模板库9-容器2-vector
开发语言·c++
励志不掉头发的内向程序员14 分钟前
C++基础——内存管理
开发语言·c++
lifallen25 分钟前
JCTools 无锁并发队列基础:ConcurrentCircularArrayQueue
java·开发语言·数据结构·算法
千里镜宵烛1 小时前
深入理解 Linux 线程:从概念到虚拟地址空间的全面解析
开发语言·c++·操作系统·线程
Eternity_GQM1 小时前
【Word VBA Zotero 引用宏错误分析与改正指南】【解决[21–23]参考文献格式插入超链接问题】
开发语言·c#·word
张柏慈2 小时前
JavaScript性能优化30招
开发语言·javascript·性能优化
promising-w2 小时前
【嵌入式C语言】六
c语言·开发语言
打不了嗝 ᥬ᭄2 小时前
Linux 信号
linux·开发语言·c++·算法
ZLRRLZ3 小时前
【C++】C++11
开发语言·c++
全栈软件开发3 小时前
PHP域名授权系统网站源码_授权管理工单系统_精美UI_附教程
开发语言·ui·php·php域名授权·授权系统网站源码