java中http调用组件深入详解
    		       		warning:
    		            这篇文章距离上次修改已过444天,其中的内容可能已经有所变动。
    		        
        		                
                在Java中,进行HTTP调用通常使用HttpURLConnection类或者第三方库如Apache HttpClient。以下是使用HttpURLConnection进行HTTP GET调用的示例代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class HttpGetExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://www.example.com");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
 
            // 设置请求头信息,如需要
            // conn.setRequestProperty("Authorization", "Bearer your-token-here");
 
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                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());
            } else {
                System.out.println("GET request not worked");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}这段代码创建了一个URL对象,然后使用openConnection方法打开一个HTTP连接。设置请求方法为GET,然后发送请求并接收响应。如果响应成功(HTTP状态码200),它将读取响应并打印。如果响应不成功,它将打印一个错误消息。这是一个非常基础的HTTP GET请求示例,对于更复杂的需求,可能需要额外的功能,如处理HTTPS、设置请求头、处理HTTP响应码、处理POST请求、上传文件等。
评论已关闭