var http = (HttpWebRequest)WebRequest.Create(url);用java怎么写
时间: 2024-04-18 17:28:31 浏览: 138
http请求的java实现
在Java中,你可以使用`HttpURLConnection`类来发送HTTP请求。下面是将C#中的代码转换为Java的示例:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
String url = "http://example.com";
try {
URL urlObj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
System.out.println(response.toString());
} else {
System.out.println("HTTP request failed. Response Code: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
上述代码会发送一个GET请求到指定的URL,并打印出服务器的响应内容。你可以根据自己的需要进行适当的修改和扩展。
阅读全文