|
7 | 7 | import java.net.URL; |
8 | 8 |
|
9 | 9 | public class HttpUtil { |
| 10 | + |
| 11 | + public static class Response { |
| 12 | + public String message; |
| 13 | + public int code; |
| 14 | + } |
10 | 15 |
|
11 | 16 | public static final String IMAGE_JPEG_CONTENT_TYPE = "image/jpeg"; |
12 | 17 |
|
13 | | - public static int uploadObject(byte[] data, String url, String contentType) throws IOException { |
14 | | - HttpURLConnection connection = (HttpURLConnection) (new URL(url).openConnection()); |
15 | | - connection.setDoOutput(true); |
16 | | - connection.setUseCaches(false); |
17 | | - connection.setRequestMethod(HttpMethod.PUT.name()); |
18 | | - connection.setRequestProperty("Content-Type", contentType); |
19 | | - OutputStream out = connection.getOutputStream(); |
20 | | - ByteArrayInputStream in = new ByteArrayInputStream(data); |
21 | | - byte[] buffer = new byte[4096]; |
22 | | - int bytesRead = -1; |
23 | | - while ((bytesRead = in.read(buffer)) != -1) { |
24 | | - out.write(buffer, 0, bytesRead); |
| 18 | + public static Response uploadObject(byte[] data, String url, String contentType) throws IOException { |
| 19 | + HttpURLConnection connection = null; |
| 20 | + Response ret = new Response(); |
| 21 | + try { |
| 22 | + connection = (HttpURLConnection) (new URL(url).openConnection()); |
| 23 | + connection.setDoOutput(true); |
| 24 | + connection.setUseCaches(false); |
| 25 | + connection.setRequestMethod(HttpMethod.PUT.name()); |
| 26 | + connection.setRequestProperty("Content-Type", contentType); |
| 27 | + OutputStream out = null; |
| 28 | + try { |
| 29 | + out = connection.getOutputStream(); |
| 30 | + ByteArrayInputStream in = new ByteArrayInputStream(data); |
| 31 | + byte[] buffer = new byte[4096]; |
| 32 | + int bytesRead = -1; |
| 33 | + while ((bytesRead = in.read(buffer)) != -1) { |
| 34 | + out.write(buffer, 0, bytesRead); |
| 35 | + } |
| 36 | + in.close(); |
| 37 | + } finally { |
| 38 | + if (out != null) { |
| 39 | + out.flush(); |
| 40 | + out.close(); |
| 41 | + } |
| 42 | + } |
| 43 | + } finally { |
| 44 | + if (connection != null) { |
| 45 | + ret.code = connection.getResponseCode(); |
| 46 | + ret.message = connection.getResponseMessage(); |
| 47 | + connection.disconnect(); |
| 48 | + } |
25 | 49 | } |
26 | | - out.flush(); |
27 | | - in.close(); |
28 | | - out.close(); |
29 | | - return connection.getResponseCode(); |
| 50 | + return ret; |
30 | 51 | } |
31 | | - |
32 | 52 | } |
0 commit comments