猿问

java发送http请求,无需等待返回结果

与B项目进行交互,由于B项目一些原因,请求处理缓慢.A项目等待返回结果需要很久...现只需发送数据无需判断发送成功失败与否,求教如何操作???以下是发送get请求的代码
publicstaticStringdoGet(StringHTTP_URL,Objectobject){
BufferedReaderreader=null;
Stringresult=null;
StringBufferhttpUrl=newStringBuffer(HTTP_URL);
StringBuffersbf=newStringBuffer();
try{
System.out.println(httpUrl.toString());
URLurl=newURL(httpUrl.toString());
HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
//请求方式设置POST
connection.setRequestMethod("GET");
//设置维持长连接
connection.setRequestProperty("Connection","Keep-Alive");
//设置文件字符集:
connection.setRequestProperty("Charset","UTF-8");
//开始连接请求
connection.connect();
OutputStreamout=connection.getOutputStream();
out.write((object.toString()).getBytes());
out.flush();
out.close();
if(connection.getResponseCode()==200){
System.out.println("连接成功,传送数据...");
InputStreamis=connection.getInputStream();
reader=newBufferedReader(newInputStreamReader(is,"UTF-8"));
StringstrRead=null;
while((strRead=reader.readLine())!=null){
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result=sbf.toString();
if(result.equals("1")){
return"1";
}elseif(result.equals("0")){
return"0";
}else{
returnresult;
}
}else{
System.out.println("连接失败,错误代码:"+connection.getResponseCode());
}
}catch(Exceptione){
e.printStackTrace();
}
returnnull;
}
慕田峪9158850
浏览 3807回答 2
2回答

浮云间

HttpURLConnection有个setReadTimeout的方法可以实现你的需求。publicstaticStringdoGet(StringHTTP_URL,Objectobject){BufferedReaderreader=null;Stringresult=null;StringBufferhttpUrl=newStringBuffer(HTTP_URL);StringBuffersbf=newStringBuffer();HttpURLConnectionconnection=null;try{System.out.println(httpUrl.toString());URLurl=newURL(httpUrl.toString());connection=(HttpURLConnection)url.openConnection();connection.setDoOutput(true);connection.setDoInput(true);//请求方式设置POSTconnection.setRequestMethod("GET");//设置维持长连接connection.setRequestProperty("Connection","Keep-Alive");//设置文件字符集:connection.setRequestProperty("Charset","UTF-8");//根据需求设置读超时的时间connection.setReadTimeout(50);//开始连接请求connection.connect();OutputStreamout=connection.getOutputStream();out.write((object.toString()).getBytes());out.flush();out.close();if(connection.getResponseCode()==200){System.out.println("连接成功,传送数据...");InputStreamis=connection.getInputStream();reader=newBufferedReader(newInputStreamReader(is,"UTF-8"));StringstrRead=null;while((strRead=reader.readLine())!=null){sbf.append(strRead);sbf.append("\r\n");}reader.close();result=sbf.toString();if(result.equals("1")){return"1";}elseif(result.equals("0")){return"0";}else{returnresult;}}else{System.out.println("连接失败,错误代码:"+connection.getResponseCode());}}catch(Exceptione){if(einstanceofSocketTimeoutException){if("Readtimedout".equals(e.getMessage())&&connection!=null&&connection.getDoOutput()){//TODO只请求不需要响应returnnull;}}e.printStackTrace();}returnnull;}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答