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

28 篇文章 0 订阅
24 篇文章 0 订阅

在上一篇中我们说了一下如何创建简单的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方法

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

https://happycoding.io/tutorials/java-server/rest-api

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

涛哥依旧在

你的鼓励是我最大的创作动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值