1
1
package com .alexbbb .uploadservice ;
2
2
3
+ import java .io .BufferedReader ;
3
4
import java .io .FileNotFoundException ;
4
5
import java .io .IOException ;
5
6
import java .io .InputStream ;
7
+ import java .io .InputStreamReader ;
6
8
import java .io .OutputStream ;
7
9
import java .io .UnsupportedEncodingException ;
8
10
import java .net .HttpURLConnection ;
@@ -154,6 +156,7 @@ private void handleFileUpload(final String uploadId, final String url, final Str
154
156
155
157
HttpURLConnection conn = null ;
156
158
OutputStream requestStream = null ;
159
+ InputStream responseStream = null ;
157
160
158
161
try {
159
162
conn = getMultipartHttpURLConnection (url , method , boundary );
@@ -168,16 +171,44 @@ private void handleFileUpload(final String uploadId, final String url, final Str
168
171
final byte [] trailer = getTrailerBytes (boundary );
169
172
requestStream .write (trailer , 0 , trailer .length );
170
173
final int serverResponseCode = conn .getResponseCode ();
171
- final String serverResponseMessage = conn .getResponseMessage ();
174
+
175
+ if (serverResponseCode / 100 == 2 ) {
176
+ responseStream = conn .getInputStream ();
177
+ } else { // getErrorStream if the response code is not 2xx
178
+ responseStream = conn .getErrorStream ();
179
+ }
180
+ final String serverResponseMessage = getResponseBodyAsString (responseStream );
172
181
173
182
broadcastCompleted (uploadId , serverResponseCode , serverResponseMessage );
174
183
175
184
} finally {
176
185
closeOutputStream (requestStream );
186
+ closeInputStream (responseStream );
177
187
closeConnection (conn );
178
188
}
179
189
}
180
190
191
+ private String getResponseBodyAsString (final InputStream inputStream ) {
192
+ StringBuilder outString = new StringBuilder ();
193
+
194
+ BufferedReader reader = null ;
195
+ try {
196
+ reader = new BufferedReader (new InputStreamReader (inputStream ));
197
+ String line ;
198
+ while ((line = reader .readLine ()) != null ) {
199
+ outString .append (line );
200
+ }
201
+ } catch (Exception exc ) {
202
+ try {
203
+ if (reader != null )
204
+ reader .close ();
205
+ } catch (Exception readerExc ) {
206
+ }
207
+ }
208
+
209
+ return outString .toString ();
210
+ }
211
+
181
212
private String getBoundary () {
182
213
final StringBuilder builder = new StringBuilder ();
183
214
0 commit comments