首页主机资讯java如何调用rest接口

java如何调用rest接口

时间2024-05-28 10:44:03发布访客分类主机资讯浏览1173
导读:在Java中调用REST接口通常使用HttpURLConnection或HttpClient来发送HTTP请求并接收响应。以下是一个简单的示例代码: 使用HttpURLConnection: import java.io.BufferedR...

在Java中调用REST接口通常使用HttpURLConnection或HttpClient来发送HTTP请求并接收响应。以下是一个简单的示例代码:

使用HttpURLConnection:

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 conn = (HttpURLConnection) url.openConnection();
    
            conn.setRequestMethod("GET");
    
            conn.setRequestProperty("Content-Type", "application/json");
    

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    
            String inputLine;
    
            StringBuffer response = new StringBuffer();


            while ((inputLine = in.readLine()) != null) {
    
                response.append(inputLine);

            }
    
            in.close();
    

            System.out.println(response.toString());

        }
 catch (Exception e) {
    
            e.printStackTrace();

        }

    }

}
    

使用HttpClient:

import org.apache.http.HttpResponse;
    
import org.apache.http.client.HttpClient;
    
import org.apache.http.client.methods.HttpGet;
    
import org.apache.http.impl.client.HttpClientBuilder;
    
import org.apache.http.util.EntityUtils;


public class RestClient {


    public static void main(String[] args) {
    
        HttpClient httpClient = HttpClientBuilder.create().build();
    
        HttpGet request = new HttpGet("http://example.com/api/resource");
    
        request.addHeader("Content-Type", "application/json");


        try {
    
            HttpResponse response = httpClient.execute(request);
    
            String responseBody = EntityUtils.toString(response.getEntity());
    
            System.out.println(responseBody);

        }
 catch (Exception e) {
    
            e.printStackTrace();

        }

    }

}
    

上述代码示例使用GET方法调用REST接口,并输出响应内容。根据实际情况,您可能需要修改HTTP方法、请求头或请求体等参数。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: java如何调用rest接口
本文地址: https://pptw.com/jishu/669855.html
java接口怎么返回json数据 php中proc_open函数的用途有哪些

游客 回复需填写必要信息