JAVA使用HTTP代码示例模板

以下是一个使用Java发送HTTP请求的示例代码:

```java

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

public class HttpExample {

public static void main(String[] args) {

try {

URL url = new URL("http://www.example.com/api");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("GET");

conn.setRequestProperty("Accept", "application/json");

if (conn.getResponseCode() != 200) {

throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());

}

BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

String output;

System.out.println("Output from Server .... \n");

while ((output = br.readLine()) != null) {

System.out.println(output);

}

conn.disconnect();

} catch (Exception e) {

e.printStackTrace();

}

}

}

```

这个示例代码使用了Java的HttpURLConnection类来发送HTTP请求。它发送了一个GET请求到指定的URL,并设置了Accept头部为application/json。如果响应码不是200,就会抛出一个运行时异常。最后,它从响应中读取数据并打印到控制台上。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个使用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、付费专栏及课程。

余额充值