Google cloud storage : length required 411 - google-cloud-storage

I use Google Cloud Storage and I want to know if my file upload is a success.
I use resumable uploads.
Google doc : google doc link
I can upload file with a session url :
byte[] byteArray = Files.readAllBytes(path);
long byteCount = byteArray.length;
//UrlForUp is my session_uri for resumable upload
String urlForUp = ObjectManager.getUrl(bucketName, objectName, properties, "image/gif", byteCount);
HttpURLConnection connection;
URL url = new URL(urlForUp);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("PUT");
connection.setRequestProperty("Content-Length", Long.toString(byteCount));
connection.connect();
OutputStream os = connection.getOutputStream();
//send file
os.write(byteArray);
os.flush();
os.close();
Map<String, List<String>> headerData;
headerData = connection.getHeaderFields();
Set listKeys = headerData.keySet();
Iterator iterator = listKeys.iterator();
System.out.println("UPLOAD RESPONSE CODE---------------------------------");
System.out.println(connection.getResponseCode());
System.out.println("UPLOAD RESPONSE HEADER---------------------------------");
while (iterator.hasNext()) {
Object key = iterator.next();
if (key != null) {
List<String> values = headerData.get(key);
for (int i = 0; i < values.size(); i++) {
if (values.get(i) != null) {
System.out.println(key.toString() + " : " + values.get(i));
}
}
}
}
Google send me 200 and my file hass been sent.
Google response :
UPLOAD RESPONSE CODE---------------------------------
200
UPLOAD RESPONSE HEADER---------------------------------
ETag : CICQ7oauzcICEAE=
Date : Wed, 17 Dec 2014 15:10:38 GMT
Vary : X-Origin
Vary : Origin
Content-Length : 810
Expires : Fri, 01 Jan 1990 00:00:00 GMT
Alternate-Protocol : 443:quic,p=0.02
Content-Type : application/json; charset=UTF-8
Server : UploadServer ("Built on Dec 2 2014 12:42:30 (1417552950)")
Pragma : no-cache
Cache-Control : no-cache, no-store, max-age=0, must-revalidate
Then I want to check this with a request.
I make a request like this : ( from google cloud doc )
PUT {session_uri} HTTP/1.1
Authorization: Bearer your_auth_token
Content-Length: 0
Content-Range: bytes */2000000
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("PUT");
Credential credential = createCredential(properties);
credential.refreshToken();
connection.setRequestProperty("Authorization", "Bearer " + credential.getAccessToken());
connection.setRequestProperty("Content-Length", "0");
connection.setRequestProperty("Content-Range","bytes */"+fileSize);
connection.connect();
System.out.println("CONNECTION MESSAGE-----------------------------------------");
System.out.println(connection.getResponseMessage());
Map<String, List<String>> headerData;
headerData = connection.getHeaderFields();
Set listKeys = headerData.keySet();
Iterator iterator = listKeys.iterator();
while (iterator.hasNext()) {
Object key = iterator.next();
if (key != null) {
List<String> values = headerData.get(key);
for (int i = 0; i < values.size(); i++) {
if (values.get(i) != null) {
System.out.println(key.toString() + " : " + values.get(i));
}
}
}
}
System.out.println(connection.getResponseCode());
Message google send me :
CONNECTION MESSAGE-----------------------------------------
Length Required
Date : Thu, 18 Dec 2014 12:12:29 GMT
Content-Length : 1428
Content-Type : text/html; charset=UTF-8
Server : GFE/2.0
411
I don't understand.
Google says me to set Content-Length to 0 and send me :
Length Required

Related

Signing issue when sending payload to Swish API

I am trying to send a payload to Swish (Swedish payment system), using TLS- and signing certificates. I am currently working with the Merchant Swish Simulator and using test-certificates from Swish documentation.
When sending the payload and signature (to endpont /api/v1/payouts) I get this error:
{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Date: Tue, 12 Apr 2022 07:02:19 GMT
Server: openresty/1.15.8.3
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Transfer-Encoding: chunked
Content-Type: application/json
}}
The code below is used to generate the signature
var payloadJson = JsonConvert.SerializeObject(payload, Formatting.None, serializerSettings);
var payloadJsonBuffer = Encoding.UTF8.GetBytes(payloadJson);
using var sha512 = SHA512.Create();
var hashedBuffer = sha512.ComputeHash(payloadJsonBuffer);
using var rsa = signCert.GetRSAPrivateKey();
var signedBuffer = rsa.SignHash(hashedBuffer, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);
var signature = Convert.ToBase64String(signedBuffer, Base64FormattingOptions.None);
var requestBody = new SwishPayoutRequestBody
{
Payload = payload,
Signature = signature
};
Does anyone have an idea to how to approach this issue or have any experience with working with Swish API using c#?
Thanks!

Wrong Content-Type in response in IErrorHandler

I would like to send response to my service in JSON format. I catch my custom errors in my custom behavior:
void IErrorHandler.ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
XDocument errorMsg = XDocument.Parse("<errorMessage>" + error.Message + "</errorMessage>");
var jsonWriter = new JsonErrorBodyWriter(errorMsg);
fault = Message.CreateMessage(version, null, jsonWriter);
fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json));
HttpResponseMessageProperty prop = new HttpResponseMessageProperty();
prop.StatusCode = HttpStatusCode.Unauthorized;
prop.Headers.Add("Content-Type", "application/json; charset=utf-8");
prop.Headers[HttpRequestHeader.ContentType] = "application/json; charset=utf-8";
--Tried different ways to achieve this
fault.Properties.Add(HttpResponseMessageProperty.Name, prop);
}
But I get wrong content-type in response. And also I couldn't manage to write any custom header like :
prop.Headers.Add("Test", "Value");
Reponse:
HTTP/1.1 401 Unauthorized
Content-Type: application/xml; charset=utf-8
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
Date: Wed, 30 Sep 2020 08:41:15 GMT
Content-Length: 37
{"description":"Autorization Failed"}
What is wrong in my code?

Downloading data from REST API response but getting a response code of -1

REST API details from documentation:
GET /REST/sql_snapshot/2003-03-01.sql.gz HTTP/1.1
Host: some.api.net
Authorization: Basic qpow3i12o3
The response shown below omits the message body, which contains binary compressed SQL data.
HTTP/1.1 200 OK
Date: Wed, 05 Mar 2003 10:19:46 GMT
Server: Apache/1.3.22 (Unix) (Red-Hat/Linux)Content-Type: application/octet-stream
I'm getting a response code of -1 from below.
URL url = new URL("https://some.api.net/REST/sql_snapshot/2003-03-01.sql.gz");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/octet-stream");
connection.setDoOutput(true);
connection.connect();

How to get last-modified from http header with dartio HttpClient

Hi there I want get Last_modified from http header with dart.io HttpClient()
code sample is:
var client = new HttpClient();
HttpClientRequest req = await client.getUrl(Uri.parse("sayagh.asnafhormozgan.ir/wp-content/tables/essentials.csv"));
var a = req.headers.value("lastModifiedHeader");
but a returns null;
how I can get Last modified?
but when I get it with curl:
curl -v "sayagh.asnafhormozgan.ir/wp-content/tables/drawer.csv"
* Trying 51.89.173.235:80...
* TCP_NODELAY set
* Connected to sayagh.asnafhormozgan.ir (51.89.173.235) port 80 (#0)
> GET /wp-content/tables/drawer.csv HTTP/1.1
> Host: sayagh.asnafhormozgan.ir
> User-Agent: curl/7.65.3
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Server: nginx
< Date: Thu, 19 Sep 2019 10:05:37 GMT
< Content-Type: text/csv
< Content-Length: 599
< Connection: keep-alive
< Last-Modified: Thu, 19 Sep 2019 09:38:30 GMT
< Accept-Ranges: bytes
< Cache-Control: max-age=0
< Expires: Thu, 19 Sep 2019 10:05:37 GMT
<
You'll need to wait for the second future to get the response, i.e.:
A getUrl request is a two-step process, triggered by two Futures. When
the first future completes with a HttpClientRequest, the underlying
network connection has been established, but no data has been sent. In
the callback function for the first future, the HTTP headers and body
can be set on the request. Either the first write to the request
object or a call to close sends the request to the server.
See https://api.dartlang.org/stable/2.5.0/dart-io/HttpClient-class.html
Also it should be 'last-modified' and not 'lastModifiedHeader' (or even better use the static const variable HttpHeaders.lastModifiedHeader), e.g.:
HttpClient client = HttpClient();
HttpClientRequest req = await client.getUrl(Uri.parse(
'http://sayagh.asnafhormozgan.ir/wp-content/tables/essentials.csv'));
HttpClientResponse response = await req.close();
print(response.headers.value(HttpHeaders.lastModifiedHeader));

LWP::UserAgent returns incomplete 2GB response message

I am using LWP::UserAgentto send request on a URL. But sometime in the response I am getting incomplete XML response.
Code
$args->{pua} = LWP::UserAgent->new();
$args->{header} = HTTP::Headers->new;
$args->{header}->header("Content-Type" => "text/xml", "SOAPAction" => $args->{soapaction});
$request = HTTP::Request->new( "POST", $args->{endpoint}, $args->{header}, $args->{xml});
$response = $args->{pua}->simple_request($request);
my $xmlResponse = $response->content;
In the $xmlResponse sometime I am getting incomplete response. Why is it happening?
ResponseHeader
Connection: close
Date: Tue, 19 May 2015 11:07:37 GMT
Server: nginx/1.6.2
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Type: text/xml;charset=ISO-8859-1
Client-Date: Tue, 19 May 2015 11:07:40 GMT
Client-Peer: 202.77.98.11:80
Client-Response-Num: 1
Client-Transfer-Encoding: chunked
X-Frame-Options: SAMEORIGIN
LWP may return incomplete response when it failed to read whole body because of the timeout or other read error. In this case $response->is_success will be true and $response->code will be 200, but response headers will contain special header called X-Died.
So you can check this header:
unless ($response->is_success) {
die "Response failed: ", $response->status_line;
}
if ($response->header('X-Died')) {
die "Response failed (internal): ", $response->header('X-Died');
}