@@ -71,39 +71,32 @@ public Response invoke(Request request, Class<? extends Response> clazz)
7171 entity .setContentType (ContentType .APPLICATION_JSON .getMimeType ());
7272 httpPost .setHeader (HTTP .CONTENT_TYPE , ContentType .APPLICATION_JSON .getMimeType ());
7373 httpPost .setEntity (entity );
74-
7574 // invoke http requesting
76- CloseableHttpResponse httpResponse ;
77- try {
78- httpResponse = this .getHttpClient ().execute (httpPost );
75+ try (CloseableHttpResponse httpResponse = this .getHttpClient ().execute (httpPost )) {
76+ String requestId = "" ;
77+ if (httpResponse .getLastHeader (HEADER_REQUEST_ID ) != null ) {
78+ requestId = httpResponse .getLastHeader (HEADER_REQUEST_ID ).getValue ();
79+ }
80+
81+ // check http status
82+ StatusLine httpStatus = httpResponse .getStatusLine ();
83+ if (httpStatus .getStatusCode () >= 400 ) {
84+ throw new UCloudException (
85+ String .format (
86+ "http error, status code %d %s" ,
87+ httpStatus .getStatusCode (), httpStatus .getReasonPhrase ()));
88+ }
89+
90+ // decode response
91+ String content = EntityUtils .toString (httpResponse .getEntity (), "UTF-8" );
92+ Response response = new Gson ().fromJson (content , clazz );
93+ response .setRequestId (requestId );
94+ return response ;
95+ } catch (UCloudException e ) {
96+ throw e ;
7997 } catch (Exception e ) {
8098 throw new TransportException ("http error" , e );
8199 }
82-
83- String requestId = "" ;
84- if (httpResponse .getLastHeader (HEADER_REQUEST_ID ) != null ) {
85- requestId = httpResponse .getLastHeader (HEADER_REQUEST_ID ).getValue ();
86- }
87-
88- // check http status
89- StatusLine httpStatus = httpResponse .getStatusLine ();
90- if (httpStatus .getStatusCode () >= 400 ) {
91- throw new UCloudException (
92- String .format (
93- "http error, status code %d %s" ,
94- httpStatus .getStatusCode (), httpStatus .getReasonPhrase ()));
95- }
96-
97- // decode response
98- String content = null ;
99- try {
100- content = EntityUtils .toString (httpResponse .getEntity (), "UTF-8" );
101- } catch (IOException e ) {
102- throw new UCloudException ("http error" , e );
103- }
104- Response response = new Gson ().fromJson (content , clazz );
105- response .setRequestId (requestId );
106- return response ;
107100 }
108101
109102 public String getBaseUrl () {
@@ -129,4 +122,9 @@ public CloseableHttpClient getHttpClient() {
129122 public void setHttpClient (CloseableHttpClient httpClient ) {
130123 this .httpClient = httpClient ;
131124 }
125+
126+ @ Override
127+ public void close () throws IOException {
128+ this .httpClient .close ();
129+ }
132130}
0 commit comments