我怎样才能重新打开HttpURLConnection

时间:2016-05-23 10:57:18

标签: java authentication httpurlconnection outputstream

我打开了HttpURLConnection连接,打开它并通过它写道:

HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
httpCon.addRequestProperty("X-Auth-Token", getAuthToken());
httpCon.addRequestProperty("Content-Type", contentType);

httpCon.setDoInput(true);
httpCon.setRequestProperty("Connection", "close");
httpCon.setReadTimeout(READ_TIMEOUT);
httpCon.setRequestProperty("Transfer-Encoding","chunked");
httpCon.setDoOutput(true);
httpCon.setChunkedStreamingMode(STREAMING_CHUNK);
OutputStream out   = httpCon.getOutputStream();

一段时间后,身份验证令牌已过期,输出流已关闭。因此,在尝试写作的时候遇到了IOException 为了解决这个问题,我试图重新进行认证并再次写入:

private void ReAuthenticate()
{
   mHttpCon.addRequestProperty("X-Auth-Token", getNewToken());
   mOutputStream = mHttpCon.getOutputStream();
}
    public void write(byte[] b) throws IOException {
      try{
         mOutputStream.write(b);
      }
      catch (IOException ex)
      {
          ReAuthenticate();
      }
  }

但是什么都写不出来? 可能有什么不对?是否保存了httCon的所有内容?例如httpCon.setDoOutput(true);

1 个答案:

答案 0 :(得分:0)

你做不到。您必须为同一URL创建一个新的。

然而,幕后有TCP连接池。