当前位置:首页 > 编程技术 > 正文

java如何调用rest接口测试

java如何调用rest接口测试

在Java中调用REST接口进行测试,通常有几种方法: 1. 使用Java内置的HttpURLConnection类```javaimport java.io.Buff...

在Java中调用REST接口进行测试,通常有几种方法:

1. 使用Java内置的HttpURLConnection类

```java

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

public class RestClient {

public static void main(String[] args) {

try {

URL url = new URL("http://example.com/api/resource");

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("GET");

connection.setRequestProperty("Content-Type", "application/json");

int responseCode = connection.getResponseCode();

System.out.println("Response Code : " + responseCode);

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String inputLine;

StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {

response.append(inputLine);

最新文章