java如何调用rest接口

29次阅读
没有评论

共计 1482 个字符,预计需要花费 4 分钟才能阅读完成。

在 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 方法、请求头或请求体等参数。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-04-13发表,共计1482字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)