[英]Simple Java Http Client program is not working
我创建了一个简单的客户端程序,但它在发送请求后不起作用并卡住了。
调试时它卡在这里 - int responseCode = httpClient.getResponseCode();
public class ScimClient {
public static void main(String[] args) throws Exception {
new ScimClient().sendGet();
}
private void sendGet() throws Exception {
String url = "https://official-joke-api.appspot.com/random_joke";
HttpURLConnection httpClient =
(HttpURLConnection) new URL(url).openConnection();
// optional default is GET
httpClient.setRequestMethod("GET");
//add request header
httpClient.setRequestProperty("Content-Type", "application/json");
int responseCode = httpClient.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
try (BufferedReader in = new BufferedReader(
new InputStreamReader(httpClient.getInputStream()))) {
StringBuilder response = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
response.append(line);
}
//print result
System.out.println(response.toString());
}
}
}
每个 HttpURLConnection 实例用于发出单个请求,但与 HTTP 服务器的底层网络连接可能由其他实例透明地共享。 在请求之后调用 HttpURLConnection 的 InputStream 或 OutputStream 上的 close() 方法可能会释放与此实例关联的网络资源,但对任何共享的持久连接没有影响。 如果持久连接当时处于空闲状态,则调用 disconnect() 方法可能会关闭底层套接字。 Java 文档
可能在调试期间,您使用相同的实例进行多次调用,这在文档中是不允许的。 您应该创建另一个实例或调用断开连接,然后再次向同一个实例调用 openConnection 以进行另一个调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.