Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 140bef1

Browse files
committed
Read server response body string
1 parent e98cd72 commit 140bef1

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

project.properties

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,5 @@
1111
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
1212

1313
# Project target.
14-
target=android-20
14+
target=android-21
1515
android.library=true

src/com/alexbbb/uploadservice/UploadService.java

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
package com.alexbbb.uploadservice;
22

3+
import java.io.BufferedReader;
34
import java.io.FileNotFoundException;
45
import java.io.IOException;
56
import java.io.InputStream;
7+
import java.io.InputStreamReader;
68
import java.io.OutputStream;
79
import java.io.UnsupportedEncodingException;
810
import java.net.HttpURLConnection;
@@ -154,6 +156,7 @@ private void handleFileUpload(final String uploadId, final String url, final Str
154156

155157
HttpURLConnection conn = null;
156158
OutputStream requestStream = null;
159+
InputStream responseStream = null;
157160

158161
try {
159162
conn = getMultipartHttpURLConnection(url, method, boundary);
@@ -168,16 +171,44 @@ private void handleFileUpload(final String uploadId, final String url, final Str
168171
final byte[] trailer = getTrailerBytes(boundary);
169172
requestStream.write(trailer, 0, trailer.length);
170173
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);
172181

173182
broadcastCompleted(uploadId, serverResponseCode, serverResponseMessage);
174183

175184
} finally {
176185
closeOutputStream(requestStream);
186+
closeInputStream(responseStream);
177187
closeConnection(conn);
178188
}
179189
}
180190

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+
181212
private String getBoundary() {
182213
final StringBuilder builder = new StringBuilder();
183214

0 commit comments

Comments
 (0)