سؤال

Following is my function to upload file GCS :

public void fileUpload(InputStream streamData, String fileName,
            String content_type) throws Exception {

    byte[] utf8Bytes = fileName.getBytes("UTF8");
    fileName = new String(utf8Bytes, "UTF8");
    URL url = new URL("http://bucketname.storage.googleapis.com"+"/"+"foldername/"+fileName);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("PUT");
    conn.setRequestProperty("Accept", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Authorization", "OAuth " + GcsToken.getAccessToken());
    conn.setRequestProperty("x-goog-meta-FileName", fileName);
    conn.setRequestProperty("x-goog-meta-ContentType", content_type);

    OutputStream os = conn.getOutputStream();

    BufferedInputStream bfis = new BufferedInputStream(streamData);
    byte[] buffer = new byte[1024];
    int bufferLength = 0;

    // now, read through the input buffer and write the contents to the file

    while ((bufferLength = bfis.read(buffer)) > 0) {
        os.write(buffer, 0, bufferLength);

    }

    System.out.println("response :: " + conn.getResponseMessage());// ?????

}

This code works fine to uplaod file, but After removing last Sysout , it is not uploading file System.out.println("response :: " + conn.getResponseMessage());

what is reason behind this ?

any help ?

thnaks

هل كانت مفيدة؟

المحلول

You need to close your OutputStream to indicate that you've finished writing the request body:

os.close();

You should also check the response code of the request:

if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
    // Error handling code here.
}

The reason it was working before is because the getResponseMessage function blocks until the request is finished being sent and the reply is received. Without ever checking the response value, your function just exits and the HTTP request might not be finished sending.

نصائح أخرى

Thanks for this clarification. I already tried with os.close() also tried with os.flush(). but same problem. :(

at last i have updated my code:

        while ((bufferLength = bfis.read(buffer)) > 0) {
            os.write(buffer, 0, bufferLength);

        }
        os.close();
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            //logger
        } 

Now I am able to upload file.

Thanks again.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top