与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);//请求方式设置POSTconnection.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;}
2 回答
浮云间
TA贡献1829条经验 获得超4个赞
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;}
添加回答
举报
0/150
提交
取消