Java代码环境,想要发起一个http的GET请求,如果想要简单的无依赖的实现(比如就使用一次的简单场景),那么使用Java原生自带的HttpURLConnection就可以实现,比较复杂且使用较多的场景,那么还是推荐使用第三方的库,例如:OKHttp,使用方法见:https://blog.terrynow.com/2021/03/09/java-http-library-okhttp3-how-to/
HttpURLConnection发起GET请求使用方法如下:
public static String httpGet(String url) throws IOException { HttpURLConnection connection = null; try { connection = (HttpURLConnection) new URL(url).openConnection(); connection.setDoOutput(true); connection.setRequestMethod("GET"); connection.setConnectTimeout(60000); connection.setReadTimeout(60000); // 可以增加其他header,key/value的方式 connection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"); int responseCode = connection.getResponseCode(); // 如果状态代码不是200,还可以从 connection.getErrorStream(); 读取错误信息 if (responseCode == 200) { return getStringFromInputStream(connection.getInputStream()); } else { throw new IOException("http get error return code: " + responseCode + ", url: " + url); } } finally { if (connection != null) { connection.disconnect(); } } } /** * 从stream流读取内容 */ private static String getStringFromInputStream(InputStream is) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); // 获取输入流 String line; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line + "\n"); } return sb.toString(); }
POST的例子详见:https://blog.terrynow.com/2022/08/06/java-no-dependency-http-url-connection-post-json-example/
文章评论