我正在尝试了解HttpURLConnection的行为,到目前为止,我必须了解所有关于连接超时,读取超时等的事情。
现在假设我已经成功打开了url连接,还有outputStream来写数据。
现在我正在尝试在服务器上写入数据,out.write(requestByte); 所以,如果我在 out.write(requestByte)行获得IOException,那么它表示什么?
请求是否已到达服务器?
try {
out.write(requestByte);
logger.info("API Request sent at : " + sdf.format(new Date()));
out.close();
} catch (IOException e) {
logger.info("Exception while writing request to output stream");
e.printStackTrace();
}
这是完整的代码......
try {
bridgeUrl = new URL(url);
if (connectionTime == null) {
connectionTime = StartupCache.getInstance().getConfigByKey(getUniqueKey(ConfigurationConstant.CONNECTION_TIME_OUT));
//connectionTime = TransactionPersistence.getInstance().getConfigByConfigKey(ConfigurationConstant.CONNECTION_TIME_OUT);
if (connectionTime != null && connectionTime.getConfigValue().trim().length() > 0) {
connectionTimeOutInMilliSec = Integer.valueOf(connectionTime.getConfigValue());
}
}
if (bridgeUrl.getProtocol().equalsIgnoreCase("https")) {
ignoreSslCertificateAuthentication();
httpConn = (HttpsURLConnection) bridgeUrl.openConnection();
} else {
httpConn = (HttpURLConnection) bridgeUrl.openConnection();
}
logger.info("\ Request : "+request+"\n");
request="JsonData="+request;
byte[] requestByte = request.getBytes();
httpConn.setRequestProperty("Content-Length", String.valueOf(requestByte.length));
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded" );
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setConnectTimeout(connectionTimeOutInMilliSec);
httpConn.setReadTimeout(connectionTimeOutInMilliSec);
out = httpConn.getOutputStream();
try {
out.write(requestByte);
logger.info("API Request sent at : " + sdf.format(new Date()));
out.close();
} catch (IOException e) {
logger.info("Exception while writing request to output stream");
e.printStackTrace();
}
}catch(MalformedURLException exMurl){
logger.info(exMurl.getMessage());
throw new ApiRequestPostingException("Exception occured while posting request to server");
}
catch(SocketTimeoutException stout){
logger.error(stout.getMessage());
stout.printStackTrace();
if (httpConn != null) {
logger.info("Closing httpConn in exception blcok of output stream connection....");
httpConn.disconnect();
}
throw new ApiRequestPostingException("Exception occured while posting request to server");
}catch(IOException ioex){
logger.error(ioex.getMessage());
ioex.printStackTrace();
if (httpConn != null) {
logger.info("Closing httpConn in exception blcok of output stream connection....");
httpConn.disconnect();
}
throw new ApiRequestPostingException("Exception occured while posting request to server");
}
答案 0 :(得分:0)
如果我在行out.write(requestByte)获得IOException,那么它表示什么?
请求是否已到达服务器?
不。它取决于你捕获的IOException
,但大多数都表明连接被致命地破坏了。如果数据已发送,或者至少缓冲到本地套接字发送缓冲区,则您将无法获得IOException
。
请注意,你必须做一些输入。您至少必须致电getResponseCode()
,然后记录结果。