我有一个应用程序,我在其中使用requestproperty连接“保持活着”调用httpURLConnection。 因为当我的应用程序崩溃时我没有调用HttpURLConnection.disconnect(),所以他没有进入断开调用,因为我没有把它放在finally方法中。
当我重新运行我的应用程序时,我看到我的url.openConnection()已经看到旧的HttpUrlConnection并将其从池中取出。现在的问题是我不能简单地杀死已经存在的连接。
在网上进行一些研究后,我发现了一个旧的错误报告(https://code.google.com/p/android/issues/detail?id=2939) 我已经尝试过不同的方法,但在调用httpURLConnection.disconnect()的url.openConnection()之后没有进行anthing。重新安装应用程序,重新启动电脑和平板电脑也无效。
所以我的问题是:如何杀死现有的HttpURLConnection?
这是错误使用代码的简短示例:
try{
File file = new File("resources/test.png");
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(urlRequest);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//Get Cookie from session
String key = MyHttpClient.sharedInstance().getCookieStore().getCookies().get(0).getName();
String value = MyHttpClient.sharedInstance().getCookieStore().getCookies().get(0).getValue();
//allow inputs & outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
//Enable GET method
connection.setRequestMethod("GET");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("User-Agent", "MyAgent");
connection.setRequestProperty("Cookie", key+"="+value);
//Call with stream fields
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
//Call with stream
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
/*outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""+ Configuration.userTempImage.getPath()+ "\""+lineEnd);
outputStream.writeBytes(lineEnd);*/
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
//Read file
bytesRead = fileInputStream.read(buffer, 0 , bufferSize);
while(bytesRead > 0){
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
/*outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);*/
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));
String jsonText = readAll(rd);
fileInputStream.close();
outputStream.flush();
outputStream.close();
System.out.print(serverResponseCode + " - " + serverResponseMessage+" -> ");
} catch (Exception ex){
System.out.print(ex.getMessage());
}
这是我的更新代码
private static String getImagePath(String urlRequest){
System.setProperty("http.keepAlive", "false");
// ?
FileOutputStream fos = null;
// The connection to the server
HttpURLConnection connection = null;
// The data steam for sending the file to the server
DataOutputStream outputStream = null;
// A file stream to read the local file.
FileInputStream fileInputStream = null;
// ?
ByteArrayOutputStream stream = null;
// Cropped image file
File croppedImage = null;
try{
try{
stream = new ByteArrayOutputStream();
Configuration.userTempBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
// Close the output-stream
if(stream != null) { stream.close(); }
croppedImage = new File(Environment.getExternalStorageDirectory(), "test.jpg");
if(croppedImage.exists()){
croppedImage.delete();
}
fos = new FileOutputStream(croppedImage);
fos.write(byteArray);
} catch (java.io.IOException e) {
Log.e("PictureDemo", "Exception in photoCallback", e);
} finally {
if(fos != null) { fos.close(); }
}
//Get Cookie from session
String key = MyHttpClient.sharedInstance().getCookieStore().getCookies().get(0).getName();
String value = MyHttpClient.sharedInstance().getCookieStore().getCookies().get(0).getValue();
URL url = new URL(urlRequest);
connection = (HttpURLConnection)url.openConnection();
//Allow inputs & outputs
connection.setDoInput(true); // <-- Exception is thrown here
connection.setDoOutput(true);
connection.setUseCaches(false);
// Set connection properties
connection.setRequestProperty("Cookie", key+"="+value);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("User-Agent", "MyAgent");
// Set connection headers
connection.setRequestMethod("GET");
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
//Call with stream fields
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
// Create an input stream to the cropped image file
fileInputStream = new FileInputStream(croppedImage);
// Create an output stream to send the file to the server
outputStream = new DataOutputStream(connection.getOutputStream());
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
//Read file
bytesRead = fileInputStream.read(buffer, 0 , bufferSize);
while(bytesRead > 0){
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// Be sure to send everything
outputStream.flush();
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));
String jsonText = RequestHelper.readAll(rd);
return jsonText;
}catch(Exception ex){
ex.printStackTrace();
} finally {
try{
if(fileInputStream != null) { fileInputStream.close(); }
if(outputStream != null) { outputStream.close(); }
}catch(Exception ex){
ex.printStackTrace();
}finally{
if(connection != null) { connection.disconnect(); }
}
}
return null;
}