java怎么调用restful接口

56次阅读
没有评论

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

Java 可以使用多种方式调用 RESTful 接口,以下是其中几种常见的方法:

  1. 使用 Java 原生的 HttpURLConnection 类来发送 HTTP 请求:
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");
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {response.append(line);
}
reader.close();
System.out.println(response.toString());
conn.disconnect();} catch (Exception e) {e.printStackTrace();
}
}
}
  1. 使用第三方库,如 Apache HttpClient 或 OkHttp:

使用 Apache HttpClient 的示例:

import org.apache.http.HttpEntity;
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) {
try {HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://example.com/api/resource");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(entity);
System.out.println(responseBody);
} catch (Exception e) {e.printStackTrace();
}
}
}

使用 OkHttp 的示例:

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class RestClient {public static void main(String[] args) {
try {OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://example.com/api/resource")
.build();
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
System.out.println(responseBody);
} catch (Exception e) {e.printStackTrace();
}
}
}

这些示例代码可以根据具体的需求进行修改和扩展。

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

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