JAVA使用HTTP代码示例模板

该代码示例展示了如何使用Java进行HTTP请求,包括GET和POST方法。GET请求通过设置URL和请求方法获取数据,而POST请求需写入请求体并设置请求方法为POST来传递数据。

这里提供一个Java实现的HTTP请求代码示例模板:

import java.net.*;
import java.io.*;

public class HttpExample {
    
    // 发送GET请求
    public static void sendGet(String url) throws Exception {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        
        con.setRequestMethod("GET");
        int responseCode = con.getResponseCode();
        System.out.println("ResponseCode: " + responseCode);
        
        BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        
        System.out.println("Response: " + response.toString());
    }
    
    // 发送POST请求
    public static void sendPost(String url, String data) throws Exception {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        
        con.setRequestMethod("POST");
        con.setDoOutput(true);
        DataOutputStream out = new DataOutputStream(con.getOutputStream());
        out.writeBytes(data);
        out.flush();
        out.close();
        
        int responseCode = con.getResponseCode();
        System.out.println("ResponseCode: " + responseCode);
        
        BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        
        System.out.println("Response: " + response.toString());
    }
    
    public static void main(String[] args) throws Exception{
        String url = "https://www.baidu.com";
        sendGet(url);
        
        url = "https://example.com/api";
        String data = "key1=value1&key2=value2";
        sendPost(url, data);
    }
}

以上代码实现了一个简单的HTTP请求,包括GET和POST两种方式。其中,GET请求通过创建URL对象和HttpURLConnection对象,并设置请求方法为GET来实现;POST请求则需要设置请求方法为POST,并通过DataOutputStream将POST数据写入请求体中。在请求完成后,获取响应内容需要通过InputStreamReader和BufferedReader来读取响应流并拼接成String。

好的,以下是一个使用Java下载模板文件的示例代码: ``` import java.io.*; import java.net.*; public class DownloadTemplate { public static void main(String[] args) { String fileUrl = "https://www.example.com/template.docx"; String saveDir = "/home/user/Documents/"; try { URL url = new URL(fileUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); int responseCode = conn.getResponseCode(); // Check if response code is OK before downloading if (responseCode == HttpURLConnection.HTTP_OK) { String fileName = ""; String disposition = conn.getHeaderField("Content-Disposition"); // Get the file name from the content-disposition header if (disposition != null) { int index = disposition.indexOf("filename="); if (index > 0) { fileName = disposition.substring(index + 10, disposition.length() - 1); } } else { fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1, fileUrl.length()); } // Create file output stream and input stream to download file String saveFilePath = saveDir + fileName; FileOutputStream outputStream = new FileOutputStream(saveFilePath); InputStream inputStream = conn.getInputStream(); byte[] buffer = new byte[4096]; int bytesRead = -1; // Download the file while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } System.out.println("File downloaded successfully"); } else { System.out.println("Failed to download file"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 这个示例代码可以从指定的URL下载文件,并将文件保存到指定的目录中。请注意,如果您想要下载的模板文件是受保护或需要授权的,则需要添加您的账户信息或令牌到请求头中,以便可以通过授权访问文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值