Closed EHG613 closed 5 years ago
class ZimgThread extends Thread { private String url; private String path; private HttpURLConnection mConnection; private long uploadedBytes; private long totalBytes; public ZimgThread(String url, String path) { this.url = url; this.path = path; } @Override public void run() { uploadedBytes = 0; totalBytes = new File(path).length(); URL urlObj; try { urlObj = new URL(url); if (urlObj.getProtocol().equals("https")) { mConnection = (HttpsURLConnection) urlObj.openConnection(); } else { mConnection = (HttpURLConnection) urlObj.openConnection(); } mConnection.setDoInput(true); mConnection.setDoOutput(true); mConnection.setConnectTimeout(15000); mConnection.setReadTimeout(15000 * 2); mConnection.setUseCaches(false); mConnection.setInstanceFollowRedirects(true); mConnection.setRequestMethod("POST"); mConnection.setRequestProperty("Content-Type", "jpeg"); mConnection.setRequestProperty("User-Agent", "AndroidUpload"); if (android.os.Build.VERSION.SDK_INT >= 19) { mConnection.setFixedLengthStreamingMode(totalBytes); } else { if (totalBytes > Integer.MAX_VALUE) throw new RuntimeException("You need Android API version 19 or newer to " + "upload more than 2GB in a single request using " + "fixed size content length. Try switching to " + "chunked mode instead, but make sure your server side supports it!"); mConnection.setFixedLengthStreamingMode((int) totalBytes); } byte[] buffer = new byte[4096]; int bytesRead; InputStream stream = new FileInputStream(new File(path)); try { while ((bytesRead = stream.read(buffer, 0, buffer.length)) > 0) { uploadedBytes += bytesRead; mConnection.getOutputStream().write(buffer, 0, bytesRead); mConnection.getOutputStream().flush(); Log.d("上传进度:", uploadedBytes * 1f / totalBytes * 100 + "%"); } } finally { stream.close(); } Logger.debug("BinaryUpload", "Server responded with HTTP " + mConnection.getResponseCode() + ":" + new String(getServerResponseBody())); } catch (Exception e) { e.printStackTrace(); } finally { if (mConnection != null) { try { mConnection.getInputStream().close(); } catch (Exception ignored) { } try { mConnection.getOutputStream().flush(); mConnection.getOutputStream().close(); } catch (Exception ignored) { } try { mConnection.disconnect(); } catch (Exception exc) { Logger.error(LOG_TAG, "Error while closing connection", exc); } } } } private byte[] getServerResponseBody() throws IOException { InputStream stream = null; try { if (mConnection.getResponseCode() / 100 == 2) { stream = mConnection.getInputStream(); } else { stream = mConnection.getErrorStream(); } return getResponseBodyAsByteArray(stream); } finally { if (stream != null) { try { stream.close(); } catch (Exception exc) { Logger.error(LOG_TAG, "Error while closing server response stream", exc); } } } } private byte[] getResponseBodyAsByteArray(final InputStream inputStream) { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); byte[] buffer = new byte[UploadService.BUFFER_SIZE]; int bytesRead; try { while ((bytesRead = inputStream.read(buffer, 0, buffer.length)) > 0) { byteStream.write(buffer, 0, bytesRead); } } catch (Exception ignored) { } return byteStream.toByteArray(); } private LinkedHashMap<String, String> getServerResponseHeaders() throws IOException { Map<String, List<String>> headers = mConnection.getHeaderFields(); if (headers == null) return null; LinkedHashMap<String, String> out = new LinkedHashMap<>(headers.size()); for (Map.Entry<String, List<String>> entry : headers.entrySet()) { if (entry.getKey() != null) { StringBuilder headerValue = new StringBuilder(); for (String value : entry.getValue()) { headerValue.append(value); } out.put(entry.getKey(), headerValue.toString()); } } return out; } }
Server responded with HTTP 200:{"ret":true,"info":{"md5":"f4f5160ffa59a169433411d1967aee4f","size":111744}}
这是一个安卓上传图片返回json串的demo
@buaazp