Example usage for java.net HttpURLConnection getRequestProperty

List of usage examples for java.net HttpURLConnection getRequestProperty

Introduction

In this page you can find the example usage for java.net HttpURLConnection getRequestProperty.

Prototype

public String getRequestProperty(String key) 

Source Link

Document

Returns the value of the named general request property for this connection.

Usage

From source file:tree.love.providers.downloads.DownloadThread.java

/**
 * Add custom headers for this download to the HTTP request.
 *//*from   www.j a va  2  s .  co m*/
private void addRequestHeaders(State state, HttpURLConnection conn) {
    for (Pair<String, String> header : mInfo.getHeaders()) {
        conn.addRequestProperty(header.first, header.second);
    }

    // Only splice in user agent when not already defined
    if (conn.getRequestProperty("User-Agent") == null) {
        conn.addRequestProperty("User-Agent", userAgent());
    }

    // Defeat transparent gzip compression, since it doesn't allow us to
    // easily resume partial downloads.
    conn.setRequestProperty("Accept-Encoding", "identity");

    if (state.mContinuingDownload) {
        if (state.mHeaderETag != null) {
            conn.addRequestProperty("If-Match", state.mHeaderETag);
        }
        conn.addRequestProperty("Range", "bytes=" + state.mCurrentBytes + "-");
    }
}

From source file:com.trk.aboutme.facebook.Request.java

final static void serializeToUrlConnection(RequestBatch requests, HttpURLConnection connection)
        throws IOException, JSONException {
    Logger logger = new Logger(LoggingBehavior.REQUESTS, "Request");

    int numRequests = requests.size();

    HttpMethod connectionHttpMethod = (numRequests == 1) ? requests.get(0).httpMethod : HttpMethod.POST;
    connection.setRequestMethod(connectionHttpMethod.name());

    URL url = connection.getURL();
    logger.append("Request:\n");
    logger.appendKeyValue("Id", requests.getId());
    logger.appendKeyValue("URL", url);
    logger.appendKeyValue("Method", connection.getRequestMethod());
    logger.appendKeyValue("User-Agent", connection.getRequestProperty("User-Agent"));
    logger.appendKeyValue("Content-Type", connection.getRequestProperty("Content-Type"));

    connection.setConnectTimeout(requests.getTimeout());
    connection.setReadTimeout(requests.getTimeout());

    // If we have a single non-POST request, don't try to serialize anything or HttpURLConnection will
    // turn it into a POST.
    boolean isPost = (connectionHttpMethod == HttpMethod.POST);
    if (!isPost) {
        logger.log();/*from  ww  w . j a  va2s  .c  o m*/
        return;
    }

    connection.setDoOutput(true);

    BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream());
    try {
        Serializer serializer = new Serializer(outputStream, logger);

        if (numRequests == 1) {
            Request request = requests.get(0);

            logger.append("  Parameters:\n");
            serializeParameters(request.parameters, serializer);

            logger.append("  Attachments:\n");
            serializeAttachments(request.parameters, serializer);

            if (request.graphObject != null) {
                processGraphObject(request.graphObject, url.getPath(), serializer);
            }
        } else {
            String batchAppID = getBatchAppId(requests);
            if (Utility.isNullOrEmpty(batchAppID)) {
                throw new FacebookException("At least one request in a batch must have an open Session, or a "
                        + "default app ID must be specified.");
            }

            serializer.writeString(BATCH_APP_ID_PARAM, batchAppID);

            // We write out all the requests as JSON, remembering which file attachments they have, then
            // write out the attachments.
            Bundle attachments = new Bundle();
            serializeRequestsAsJSON(serializer, requests, attachments);

            logger.append("  Attachments:\n");
            serializeAttachments(attachments, serializer);
        }
    } finally {
        outputStream.close();
    }

    logger.log();
}

From source file:com.db.comserv.main.utilities.HttpCaller.java

@Override
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "DM_DEFAULT_ENCODING")
public HttpResult runRequest(String type, String methodType, URL url, List<Map<String, String>> headers,
        String requestBody, String sslByPassOption, int connTimeOut, int readTimeout, HttpServletRequest req)
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException,
        UnsupportedEncodingException, IOException, UnknownHostException, URISyntaxException {

    StringBuffer response = new StringBuffer();
    HttpResult httpResult = new HttpResult();
    boolean gzip = false;
    final long startNano = System.nanoTime();
    try {//w  w  w  . ja v  a 2 s.co  m
        URL encodedUrl = new URL(Utility.encodeUrl(url.toString()));
        HttpURLConnection con = (HttpURLConnection) encodedUrl.openConnection();
        TrustModifier.relaxHostChecking(con, sslByPassOption);

        // connection timeout 5s
        con.setConnectTimeout(connTimeOut);

        // read timeout 10s
        con.setReadTimeout(readTimeout * getQueryCost(req));

        methodType = methodType.toUpperCase();
        con.setRequestMethod(methodType);

        sLog.debug("Performing '{}' to '{}'", methodType, ServletUtil.filterUrl(url.toString()));

        // Get headers & set request property
        for (int i = 0; i < headers.size(); i++) {
            Map<String, String> header = headers.get(i);
            con.setRequestProperty(header.get("headerKey").toString(), header.get("headerValue").toString());
            sLog.debug("Setting Header '{}' with value '{}'", header.get("headerKey").toString(),
                    ServletUtil.filterHeaderValue(header.get("headerKey").toString(),
                            header.get("headerValue").toString()));
        }

        if (con.getRequestProperty("Accept-Encoding") == null) {
            con.setRequestProperty("Accept-Encoding", "gzip");
        }

        if (requestBody != null && !requestBody.equals("")) {
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.write(Utility.toUtf8Bytes(requestBody));
            wr.flush();
            wr.close();

        }

        // push response
        BufferedReader in = null;
        String inputLine;

        List<String> contentEncoding = con.getHeaderFields().get("Content-Encoding");
        if (contentEncoding != null) {
            for (String val : contentEncoding) {
                if ("gzip".equalsIgnoreCase(val)) {
                    sLog.debug("Gzip enabled response");
                    gzip = true;
                    break;
                }
            }
        }

        sLog.debug("Response: '{} {}' with headers '{}'", con.getResponseCode(), con.getResponseMessage(),
                ServletUtil.buildHeadersForLog(con.getHeaderFields()));

        if (con.getResponseCode() != 200 && con.getResponseCode() != 201) {
            if (con.getErrorStream() != null) {
                if (gzip) {
                    in = new BufferedReader(
                            new InputStreamReader(new GZIPInputStream(con.getErrorStream()), "UTF-8"));
                } else {
                    in = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8"));
                }
            }
        } else {
            String[] urlParts = url.toString().split("\\.");
            if (urlParts.length > 1) {
                String ext = urlParts[urlParts.length - 1];
                if (ext.equalsIgnoreCase("png") || ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("jpeg")
                        || ext.equalsIgnoreCase("gif")) {
                    BufferedImage imBuff;
                    if (gzip) {
                        imBuff = ImageIO.read(new GZIPInputStream(con.getInputStream()));
                    } else {
                        BufferedInputStream bfs = new BufferedInputStream(con.getInputStream());
                        imBuff = ImageIO.read(bfs);
                    }
                    BufferedImage newImage = new BufferedImage(imBuff.getWidth(), imBuff.getHeight(),
                            BufferedImage.TYPE_3BYTE_BGR);

                    // converting image to greyScale
                    int width = imBuff.getWidth();
                    int height = imBuff.getHeight();
                    for (int i = 0; i < height; i++) {
                        for (int j = 0; j < width; j++) {
                            Color c = new Color(imBuff.getRGB(j, i));
                            int red = (int) (c.getRed() * 0.21);
                            int green = (int) (c.getGreen() * 0.72);
                            int blue = (int) (c.getBlue() * 0.07);
                            int sum = red + green + blue;
                            Color newColor = new Color(sum, sum, sum);
                            newImage.setRGB(j, i, newColor.getRGB());
                        }
                    }

                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    ImageIO.write(newImage, "jpg", out);
                    byte[] bytes = out.toByteArray();

                    byte[] encodedBytes = Base64.encodeBase64(bytes);
                    String base64Src = new String(encodedBytes);
                    int imageSize = ((base64Src.length() * 3) / 4) / 1024;
                    int initialImageSize = imageSize;
                    int maxImageSize = Integer.parseInt(properties.getValue("Reduced_Image_Size"));
                    float quality = 0.9f;
                    if (!(imageSize <= maxImageSize)) {
                        //This means that image size is greater and needs to be reduced.
                        sLog.debug("Image size is greater than " + maxImageSize + " , compressing image.");
                        while (!(imageSize < maxImageSize)) {
                            base64Src = compress(base64Src, quality);
                            imageSize = ((base64Src.length() * 3) / 4) / 1024;
                            quality = quality - 0.1f;
                            DecimalFormat df = new DecimalFormat("#.0");
                            quality = Float.parseFloat(df.format(quality));
                            if (quality <= 0.1) {
                                break;
                            }
                        }
                    }
                    sLog.debug("Initial image size was : " + initialImageSize + " Final Image size is : "
                            + imageSize + "Url is : " + url + "quality is :" + quality);
                    String src = "data:image/" + urlParts[urlParts.length - 1] + ";base64,"
                            + new String(base64Src);
                    JSONObject joResult = new JSONObject();
                    joResult.put("Image", src);
                    out.close();
                    httpResult.setResponseCode(con.getResponseCode());
                    httpResult.setResponseHeader(con.getHeaderFields());
                    httpResult.setResponseBody(joResult.toString());
                    httpResult.setResponseMsg(con.getResponseMessage());
                    return httpResult;
                }
            }

            if (gzip) {
                in = new BufferedReader(
                        new InputStreamReader(new GZIPInputStream(con.getInputStream()), "UTF-8"));
            } else {
                in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            }
        }
        if (in != null) {
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        }

        httpResult.setResponseCode(con.getResponseCode());
        httpResult.setResponseHeader(con.getHeaderFields());
        httpResult.setResponseBody(response.toString());
        httpResult.setResponseMsg(con.getResponseMessage());

    } catch (Exception e) {
        sLog.error("Failed to received HTTP response after timeout", e);

        httpResult.setTimeout(true);
        httpResult.setResponseCode(500);
        httpResult.setResponseMsg("Internal Server Error Timeout");
        return httpResult;
    }

    return httpResult;
}

From source file:com.salesmanBuddy.dao.JDBCSalesmanBuddyDAO.java

public GoogleUserInfo getGoogleUserInfo(String token) throws GoogleUserInfoException {
    URL url;/* www. j a v a  2  s .co  m*/
    byte[] body = null;
    JSONObject json = null;
    String whatItHas = "";
    try {
        url = new URL(GoogleUserEndpoint);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("GET");

        conn.setRequestProperty("Authorization", token);
        whatItHas = conn.getRequestProperty("Authorization");

        body = IOUtils.toByteArray(conn.getInputStream());
        json = new JSONObject(new String(body));

    } catch (ProtocolException pe) {
        throw new RuntimeException("protocolExceptions: " + pe.getLocalizedMessage());
    } catch (MalformedURLException e) {
        throw new RuntimeException("malformedUrlException: " + e.getLocalizedMessage());
    } catch (IOException e) {
        throw new RuntimeException("IOException: " + e.getLocalizedMessage() + ", token:" + token + ", auth:"
                + whatItHas + ", json: " + json + ", e: " + e);
    } catch (JSONException jse) {
        throw new RuntimeException("JSONException: " + jse.getLocalizedMessage());
    }
    GoogleUserInfo gui = new GoogleUserInfo(json);
    return gui;
}

From source file:com.lewa.crazychapter11.MainActivity.java

private void getInput() {
    try {/* www  . j  a v  a  2s  .c  o m*/
        URL url = new URL("http://www.google.cn/");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setConnectTimeout(10000);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("accept", "*/*");
        String location = conn.getRequestProperty("location");
        Log.i("algerheHttp", "location=" + location);
        int resCode = conn.getResponseCode();
        conn.connect();
        InputStream stream = conn.getInputStream();
        byte[] data = new byte[102400];
        int length = stream.read(data);
        String str = new String(data, 0, length);
        conn.disconnect();
        // System.out.println(str);
        Log.i("algerheHttp", "str=" + str);
        stream.close();
    } catch (Exception ee) {
        System.out.print("ee:" + ee.getMessage());
    }
}

From source file:com.facebook.GraphRequest.java

final static void serializeToUrlConnection(GraphRequestBatch requests, HttpURLConnection connection)
        throws IOException, JSONException {
    Logger logger = new Logger(LoggingBehavior.REQUESTS, "Request");

    int numRequests = requests.size();
    boolean shouldUseGzip = isGzipCompressible(requests);

    HttpMethod connectionHttpMethod = (numRequests == 1) ? requests.get(0).httpMethod : HttpMethod.POST;
    connection.setRequestMethod(connectionHttpMethod.name());
    setConnectionContentType(connection, shouldUseGzip);

    URL url = connection.getURL();
    logger.append("Request:\n");
    logger.appendKeyValue("Id", requests.getId());
    logger.appendKeyValue("URL", url);
    logger.appendKeyValue("Method", connection.getRequestMethod());
    logger.appendKeyValue("User-Agent", connection.getRequestProperty("User-Agent"));
    logger.appendKeyValue("Content-Type", connection.getRequestProperty("Content-Type"));

    connection.setConnectTimeout(requests.getTimeout());
    connection.setReadTimeout(requests.getTimeout());

    // If we have a single non-POST request, don't try to serialize anything or
    // HttpURLConnection will turn it into a POST.
    boolean isPost = (connectionHttpMethod == HttpMethod.POST);
    if (!isPost) {
        logger.log();//from w  w w. j  av  a2s.  co  m
        return;
    }

    connection.setDoOutput(true);

    OutputStream outputStream = null;
    try {
        outputStream = new BufferedOutputStream(connection.getOutputStream());
        if (shouldUseGzip) {
            outputStream = new GZIPOutputStream(outputStream);
        }

        if (hasOnProgressCallbacks(requests)) {
            ProgressNoopOutputStream countingStream = null;
            countingStream = new ProgressNoopOutputStream(requests.getCallbackHandler());
            processRequest(requests, null, numRequests, url, countingStream, shouldUseGzip);

            int max = countingStream.getMaxProgress();
            Map<GraphRequest, RequestProgress> progressMap = countingStream.getProgressMap();

            outputStream = new ProgressOutputStream(outputStream, requests, progressMap, max);
        }

        processRequest(requests, logger, numRequests, url, outputStream, shouldUseGzip);
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
    }

    logger.log();
}

From source file:com.google.ytd.SubmitActivity.java

private String gdataUpload(File file, String uploadUrl, int start, int end) throws IOException {
    int chunk = end - start + 1;
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];
    FileInputStream fileStream = new FileInputStream(file);

    HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl);
    // some mobile proxies do not support PUT, using X-HTTP-Method-Override to get around this problem
    if (isFirstRequest()) {
        Log.d(LOG_TAG, String.format("Uploaded %d bytes so far, using POST method.", (int) totalBytesUploaded));
        urlConnection.setRequestMethod("POST");
    } else {//from  w  ww.j a  v  a  2  s.  co  m
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT");
        Log.d(LOG_TAG,
                String.format("Uploaded %d bytes so far, using POST with X-HTTP-Method-Override PUT method.",
                        (int) totalBytesUploaded));
    }
    urlConnection.setDoOutput(true);
    urlConnection.setFixedLengthStreamingMode(chunk);
    urlConnection.setRequestProperty("Content-Type", "video/3gpp");
    urlConnection.setRequestProperty("Content-Range",
            String.format("bytes %d-%d/%d", start, end, file.length()));
    Log.d(LOG_TAG, urlConnection.getRequestProperty("Content-Range"));

    OutputStream outStreamWriter = urlConnection.getOutputStream();

    fileStream.skip(start);

    int bytesRead;
    int totalRead = 0;
    while ((bytesRead = fileStream.read(buffer, 0, bufferSize)) != -1) {
        outStreamWriter.write(buffer, 0, bytesRead);
        totalRead += bytesRead;
        this.totalBytesUploaded += bytesRead;

        double percent = (totalBytesUploaded / currentFileSize) * 99;

        /*
        Log.d(LOG_TAG, String.format(
        "fileSize=%f totalBytesUploaded=%f percent=%f", currentFileSize,
        totalBytesUploaded, percent));
        */

        dialog.setProgress((int) percent);

        if (totalRead == (end - start + 1)) {
            break;
        }
    }

    outStreamWriter.close();

    int responseCode = urlConnection.getResponseCode();

    Log.d(LOG_TAG, "responseCode=" + responseCode);
    Log.d(LOG_TAG, "responseMessage=" + urlConnection.getResponseMessage());

    try {
        if (responseCode == 201) {
            String videoId = parseVideoId(urlConnection.getInputStream());

            String latLng = null;
            if (this.videoLocation != null) {
                latLng = String.format("lat=%f lng=%f", this.videoLocation.getLatitude(),
                        this.videoLocation.getLongitude());
            }

            submitToYtdDomain(this.ytdDomain, this.assignmentId, videoId, this.youTubeName,
                    SubmitActivity.this.clientLoginToken, getTitleText(), getDescriptionText(), this.dateTaken,
                    latLng, this.tags);
            dialog.setProgress(100);
            return videoId;
        } else if (responseCode == 200) {
            Set<String> keySet = urlConnection.getHeaderFields().keySet();
            String keys = urlConnection.getHeaderFields().keySet().toString();
            Log.d(LOG_TAG, String.format("Headers keys %s.", keys));
            for (String key : keySet) {
                Log.d(LOG_TAG,
                        String.format("Header key %s value %s.", key, urlConnection.getHeaderField(key)));
            }
            Log.w(LOG_TAG, "Received 200 response during resumable uploading");
            throw new IOException(String.format("Unexpected response code : responseCode=%d responseMessage=%s",
                    responseCode, urlConnection.getResponseMessage()));
        } else {
            if ((responseCode + "").startsWith("5")) {
                String error = String.format("responseCode=%d responseMessage=%s", responseCode,
                        urlConnection.getResponseMessage());
                Log.w(LOG_TAG, error);
                // TODO - this exception will trigger retry mechanism to kick in
                // TODO - even though it should not, consider introducing a new type so
                // TODO - resume does not kick in upon 5xx
                throw new IOException(error);
            } else if (responseCode == 308) {
                // OK, the chunk completed succesfully 
                Log.d(LOG_TAG, String.format("responseCode=%d responseMessage=%s", responseCode,
                        urlConnection.getResponseMessage()));
            } else {
                // TODO - this case is not handled properly yet
                Log.w(LOG_TAG, String.format("Unexpected return code : %d %s while uploading :%s", responseCode,
                        urlConnection.getResponseMessage(), uploadUrl));
            }
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.apache.hadoop.crypto.key.kms.KMSClientProvider.java

private <T> T call(HttpURLConnection conn, Map jsonOutput, int expectedResponse, Class<T> klass,
        int authRetryCount) throws IOException {
    T ret = null;/* w w w .ja v a 2 s. c  om*/
    try {
        if (jsonOutput != null) {
            writeJson(jsonOutput, conn.getOutputStream());
        }
    } catch (IOException ex) {
        IOUtils.closeStream(conn.getInputStream());
        throw ex;
    }
    if ((conn.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN
            && (conn.getResponseMessage().equals(ANONYMOUS_REQUESTS_DISALLOWED)
                    || conn.getResponseMessage().contains(INVALID_SIGNATURE)))
            || conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
        // Ideally, this should happen only when there is an Authentication
        // failure. Unfortunately, the AuthenticationFilter returns 403 when it
        // cannot authenticate (Since a 401 requires Server to send
        // WWW-Authenticate header as well)..
        KMSClientProvider.this.authToken = new DelegationTokenAuthenticatedURL.Token();
        if (authRetryCount > 0) {
            String contentType = conn.getRequestProperty(CONTENT_TYPE);
            String requestMethod = conn.getRequestMethod();
            URL url = conn.getURL();
            conn = createConnection(url, requestMethod);
            conn.setRequestProperty(CONTENT_TYPE, contentType);
            return call(conn, jsonOutput, expectedResponse, klass, authRetryCount - 1);
        }
    }
    try {
        AuthenticatedURL.extractToken(conn, authToken);
    } catch (AuthenticationException e) {
        // Ignore the AuthExceptions.. since we are just using the method to
        // extract and set the authToken.. (Workaround till we actually fix
        // AuthenticatedURL properly to set authToken post initialization)
    }
    HttpExceptionUtils.validateResponse(conn, expectedResponse);
    if (conn.getContentType() != null
            && conn.getContentType().trim().toLowerCase().startsWith(APPLICATION_JSON_MIME) && klass != null) {
        ObjectMapper mapper = new ObjectMapper();
        InputStream is = null;
        try {
            is = conn.getInputStream();
            ret = mapper.readValue(is, klass);
        } finally {
            IOUtils.closeStream(is);
        }
    }
    return ret;
}

From source file:com.facebook.Request.java

final static void serializeToUrlConnection(RequestBatch requests, HttpURLConnection connection)
        throws IOException, JSONException {
    Logger logger = new Logger(LoggingBehavior.REQUESTS, "Request");

    int numRequests = requests.size();
    boolean shouldUseGzip = isGzipCompressible(requests);

    HttpMethod connectionHttpMethod = (numRequests == 1) ? requests.get(0).httpMethod : HttpMethod.POST;
    connection.setRequestMethod(connectionHttpMethod.name());
    setConnectionContentType(connection, shouldUseGzip);

    URL url = connection.getURL();
    logger.append("Request:\n");
    logger.appendKeyValue("Id", requests.getId());
    logger.appendKeyValue("URL", url);
    logger.appendKeyValue("Method", connection.getRequestMethod());
    logger.appendKeyValue("User-Agent", connection.getRequestProperty("User-Agent"));
    logger.appendKeyValue("Content-Type", connection.getRequestProperty("Content-Type"));

    connection.setConnectTimeout(requests.getTimeout());
    connection.setReadTimeout(requests.getTimeout());

    // If we have a single non-POST request, don't try to serialize anything or HttpURLConnection will
    // turn it into a POST.
    boolean isPost = (connectionHttpMethod == HttpMethod.POST);
    if (!isPost) {
        logger.log();/*from   w ww  .j  ava 2  s. c o  m*/
        return;
    }

    connection.setDoOutput(true);

    OutputStream outputStream = null;
    try {
        outputStream = new BufferedOutputStream(connection.getOutputStream());
        if (shouldUseGzip) {
            outputStream = new GZIPOutputStream(outputStream);
        }

        if (hasOnProgressCallbacks(requests)) {
            ProgressNoopOutputStream countingStream = null;
            countingStream = new ProgressNoopOutputStream(requests.getCallbackHandler());
            processRequest(requests, null, numRequests, url, countingStream, shouldUseGzip);

            int max = countingStream.getMaxProgress();
            Map<Request, RequestProgress> progressMap = countingStream.getProgressMap();

            outputStream = new ProgressOutputStream(outputStream, requests, progressMap, max);
        }

        processRequest(requests, logger, numRequests, url, outputStream, shouldUseGzip);
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
    }

    logger.log();
}

From source file:com.BeatYourRecord.SubmitActivity.java

private String gdataUpload(File file, String uploadUrl, int start, int end) throws IOException {
    int chunk = end - start + 1;
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];
    FileInputStream fileStream = new FileInputStream(file);

    HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl);
    // some mobile proxies do not support PUT, using X-HTTP-Method-Override to get around this problem
    if (isFirstRequest()) {
        Log.d(LOG_TAG, String.format("Uploaded %d bytes so far, using POST method.", (int) totalBytesUploaded));
        urlConnection.setRequestMethod("POST");
    } else {/*from www.  ja  v a 2s. co  m*/
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT");
        Log.d(LOG_TAG,
                String.format("Uploaded %d bytes so far, using POST with X-HTTP-Method-Override PUT method.",
                        (int) totalBytesUploaded));
    }
    urlConnection.setDoOutput(true);
    urlConnection.setFixedLengthStreamingMode(chunk);
    urlConnection.setRequestProperty("Content-Type", "video/3gpp");
    urlConnection.setRequestProperty("Content-Range",
            String.format("bytes %d-%d/%d", start, end, file.length()));
    Log.d(LOG_TAG, urlConnection.getRequestProperty("Content-Range"));
    //////may be
    //log.v("id man id",urlConnection.getRequestProperty("Content-Range"));
    OutputStream outStreamWriter = urlConnection.getOutputStream();

    fileStream.skip(start);

    int bytesRead;
    int totalRead = 0;
    while ((bytesRead = fileStream.read(buffer, 0, bufferSize)) != -1) {
        outStreamWriter.write(buffer, 0, bytesRead);
        totalRead += bytesRead;
        this.totalBytesUploaded += bytesRead;

        double percent = (totalBytesUploaded / currentFileSize) * 99;

        /*
        Log.d(LOG_TAG, String.format(
        "fileSize=%f totalBytesUploaded=%f percent=%f", currentFileSize,
        totalBytesUploaded, percent));
        */

        dialog.setProgress((int) percent);

        if (totalRead == (end - start + 1)) {
            break;
        }
    }

    outStreamWriter.close();

    int responseCode = urlConnection.getResponseCode();

    Log.d(LOG_TAG, "responseCode=" + responseCode);
    Log.d(LOG_TAG, "responseMessage=" + urlConnection.getResponseMessage());

    try {
        if (responseCode == 201) {
            String videoId = parseVideoId(urlConnection.getInputStream());
            //log.v("Video ID", videoId);
            vidId = videoId;
            String latLng = null;
            if (this.videoLocation != null) {
                latLng = String.format("lat=%f lng=%f", this.videoLocation.getLatitude(),
                        this.videoLocation.getLongitude());
            }

            submitToYtdDomain(this.ytdDomain, this.assignmentId, videoId, this.youTubeName,
                    SubmitActivity.this.clientLoginToken, getTitleText(), getDescriptionText(), this.dateTaken,
                    latLng, this.tags);
            dialog.setProgress(100);
            //log.v("10video id",videoId);
            return videoId;
        } else if (responseCode == 200) {
            Set<String> keySet = urlConnection.getHeaderFields().keySet();
            String keys = urlConnection.getHeaderFields().keySet().toString();
            Log.d(LOG_TAG, String.format("Headers keys %s.", keys));
            //////////////may be
            for (String key : keySet) {
                Log.d(LOG_TAG,
                        String.format("Header key %s value %s.", key, urlConnection.getHeaderField(key)));
            }
            Log.w(LOG_TAG, "Received 200 response during resumable uploading");
            throw new IOException(String.format("Unexpected response code : responseCode=%d responseMessage=%s",
                    responseCode, urlConnection.getResponseMessage()));
        } else {
            if ((responseCode + "").startsWith("5")) {
                String error = String.format("responseCode=%d responseMessage=%s", responseCode,
                        urlConnection.getResponseMessage());
                Log.w(LOG_TAG, error);
                // TODO - this exception will trigger retry mechanism to kick in
                // TODO - even though it should not, consider introducing a new type so
                // TODO - resume does not kick in upon 5xx
                throw new IOException(error);
            } else if (responseCode == 308) {
                // OK, the chunk completed succesfully 
                Log.d(LOG_TAG, String.format("responseCode=%d responseMessage=%s", responseCode,
                        urlConnection.getResponseMessage()));
            } else {
                // TODO - this case is not handled properly yet
                Log.w(LOG_TAG, String.format("Unexpected return code : %d %s while uploading :%s", responseCode,
                        urlConnection.getResponseMessage(), uploadUrl));
            }
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }

    return null;
}