Java多线程发送http请求
时间: 2023-07-31 16:14:03 浏览: 49
在Java中,可以使用多线程来发送HTTP请求。以下是一个简单的示例代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpThread extends Thread {
private String url;
public HttpThread(String url) {
this.url = url;
}
@Override
public void run() {
try {
URL urlObj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
conn.setRequestMethod("GET");
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 from " + url + ": " + response.toString());
} else {
System.out.println("Request failed for URL : " + url);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
HttpThread thread1 = new HttpThread("http://www.example.com");
HttpThread thread2 = new HttpThread("http://www.example.org");
thread1.start();
thread2.start();
}
}
```
在上面的代码中,我们创建了一个名为`HttpThread`的自定义线程类,该类继承自`Thread`类。在`run`方法中,我们使用`HttpURLConnection`发送HTTP GET请求,并将响应内容打印到控制台。
在`main`方法中,我们创建了两个`HttpThread`对象,并分别设置不同的URL。然后,我们通过调用`start`方法来启动这两个线程,从而实现多线程发送HTTP请求。
请注意,这只是一个简单的示例,实际使用中可能需要根据具体需求进行适当的修改和扩展。