HttpURLConnection的关闭链接写在finally里防止报错不关闭占用资源

 
HttpURLConnection httpConnection=null;
		try {
			byte[] signBytes;
			respEncode = Base64.encode(text.getBytes("UTF-8"));
			signBytes = "message";
			
			// 建立一个HttpURLConnection
			httpConnection = (HttpURLConnection) new URL(pathUrl).openConnection();
			httpConnection.setRequestMethod("POST");
			httpConnection.setDoOutput(true);
			httpConnection.setDoInput(true);
			httpConnection.setAllowUserInteraction(true);
			httpConnection.setReadTimeout(120000);
			httpConnection.setConnectTimeout(120000);
			httpConnection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
			httpConnection.connect();
			
			// 发送数据
			OutputStream outputStream = httpConnection.getOutputStream();
			byte[] buffer = text.getBytes("UTF-8"); // 平台生成的XML串
			outputStream.write(buffer);
			outputStream.flush();
			outputStream.close();
			// 接收数据数据
			@SuppressWarnings("resource")
			Scanner scanner = new Scanner(httpConnection.getInputStream(), "UTF-8");
			while (scanner.hasNextLine())
			{
				responseStr+=scanner.nextLine();
			}
			System.out.println(responseStr);
			return responseStr;
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
            if(httpConnection!=null)
			    httpConnection.disconnect();
		}

 

你可能感兴趣的:(Java)