使用httpurlconnection(原生api)
httpurlconnection是java标准库提供的http客户端,适合简单请求。
public class httpurlconnectionexample { public static void main(string[] args) throws exception { url url = new url("https://api.example.com/data"); httpurlconnection conn = (httpurlconnection) url.openconnection(); conn.setrequestmethod("get"); int responsecode = conn.getresponsecode(); bufferedreader in = new bufferedreader(new inputstreamreader(conn.getinputstream())); string inputline; stringbuilder response = new stringbuilder(); while ((inputline = in.readline()) != null) { response.append(inputline); } in.close(); system.out.println(response.tostring()); } }
使用apache httpclient
apache httpclient是功能更丰富的第三方库,适合复杂场景。
public class apachehttpclientexample { public static void main(string[] args) throws exception { closeablehttpclient httpclient = httpclients.createdefault(); httpget request = new httpget("https://api.example.com/data"); try (closeablehttpresponse response = httpclient.execute(request)) { string result = entityutils.tostring(response.getentity()); system.out.println(result); } } }
使用okhttp
okhttp是square开发的现代http客户端,性能优异且api简洁。
public class okhttpexample { public static void main(string[] args) throws exception { okhttpclient client = new okhttpclient(); request request = new request.builder() .url("https://api.example.com/data") .build(); try (response response = client.newcall(request).execute()) { system.out.println(response.body().string()); } } }
使用java 11+的httpclient
java 11引入的新http客户端,支持异步和http/2。
public class java11httpclientexample { public static void main(string[] args) throws exception { httpclient client = httpclient.newhttpclient(); httprequest request = httprequest.newbuilder() .uri(uri.create("https://api.example.com/data")) .build(); httpresponse<string> response = client.send( request, httpresponse.bodyhandlers.ofstring()); system.out.println(response.body()); } }
处理post请求(以okhttp为例)
post请求需要构建请求体,以下是json提交示例。
public class okhttppostexample { public static void main(string[] args) throws exception { okhttpclient client = new okhttpclient(); mediatype json = mediatype.get("application/json; charset=utf-8"); string jsonbody = "{\"name\":\"john\", \"age\":30}"; request request = new request.builder() .url("https://api.example.com/post") .post(requestbody.create(jsonbody, json)) .build(); try (response response = client.newcall(request).execute()) { system.out.println(response.body().string()); } } }
总结对比
方法 | 特点 | 适用场景 |
---|---|---|
httpurlconnection | 原生支持,无需依赖 | 简单get/post请求 |
apache httpclient | 功能全面,支持连接池 | 企业级复杂http交互 |
okhttp | 高性能,简洁api | 移动端/高性能需求 |
java 11 httpclient | 现代api,支持异步和http/2 | java 11+项目 |
可根据项目实际需求选择合适的方法。在现代项目推荐使用okhttp或java 11+ httpclient。
到此这篇关于java实现发起http请求的四种方法实现与适用场景的文章就介绍到这了,更多相关java发起http请求内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论