Java在新线程中使用openConnection挂起
我正在构建一个应用程序,它在单独的线程中调用RESTAPI的API请求。调用调用后,此应用程序仍挂起-未引发异常 我尝试了很多方法从我的Java应用程序中发出GET请求,但没有一个成功Java在新线程中使用openConnection挂起,java,http,Java,Http,我正在构建一个应用程序,它在单独的线程中调用RESTAPI的API请求。调用调用后,此应用程序仍挂起-未引发异常 我尝试了很多方法从我的Java应用程序中发出GET请求,但没有一个成功 classthreadrunner{ 公共ThreadRunner(){ } 公共静态void main(字符串[]args){ ThreadRunner ThreadRunner=新的ThreadRunner(); threadRunner.startChecking(); } 公共无效开始检查(){ Thre
classthreadrunner{
公共ThreadRunner(){
}
公共静态void main(字符串[]args){
ThreadRunner ThreadRunner=新的ThreadRunner();
threadRunner.startChecking();
}
公共无效开始检查(){
Thread Thread=新线程(new Runnable(){
@凌驾
公开募捐{
APIUtils.sendGet(“https://app01.mysimpledomain.abc/api/v2/user/1");
}
});
thread.setName(“ThreadRunner”);
//setDaemon(true);
thread.start();
}
}
类aputils{
公共静态void sendGet(字符串url){
试一试{
System.out.println(“在调用我的url之前…”);
URL obj=新URL(URL);
HttpURLConnection con=(HttpURLConnection)obj.openConnection();
//可选默认值是GET
con.setRequestMethod(“GET”);
//添加请求头
con.setRequestProperty(“用户代理”,用户代理);
int responseCode=con.getResponseCode();
System.out.println(“\n向URL发送'GET'请求:“+URL”);
System.out.println(“响应代码:“+responseCode”);
BufferedReader in=新的BufferedReader(新的InputStreamReader(con.getInputStream());
字符串输入线;
StringBuffer响应=新的StringBuffer();
而((inputLine=in.readLine())!=null){
追加(inputLine);
}
in.close();
System.out.println(“响应:+response.toString());
System.out.println(response.toString());
}捕获(HttpStatusCodeException){
System.out.println(“HttpStatusCodeException e:+e.getMessage());
}捕获(例外e){
System.out.println(“异常e:+e.getMessage());
//日志错误(e,e);
}
}
}
打印“连接前…”后消息停止。我应该看到API的输出
我想说的是,api调用可以在chrome/firefox/postman上运行
编辑:
方法APIUtils.sendGet:的URL有效,但我的API URL在此之前挂起
编辑2:
我API中的URL工作正常,并在Chrome/Firefox/Postman中提供JSON。它可能引发异常。编写代码以捕获特定异常并尝试解决它。 这是工作代码
String url = "http://www.google.com/search?q=mkyong";
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + 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.toString());
} catch (HttpStatusCodeException e) {
attempts++;
} catch (Exception e) {
LOG.error(e, e);
}
这在不使用新线程的情况下工作吗?尝试使用try-catch块。startCheck()方法完全不起任何作用。我添加了其他代码-请现在检查为什么设置线程守护进程?这意味着应用程序将在不让其完成的情况下退出。在这种情况下,可能连开始的机会都没有。@matt“线程守护进程”是什么意思?你能说得更多吗?这是可行的,但当我将url变量更改为API get请求时,它在try块之前停止了。你知道为什么吗?