Am using below url to upload a file to dropbox using oauth and am getting an error
{"error": "Call requires one of the following methods: PUT, POST, got GET!"}
am passing httpmethod as PUT but still asking the error.
Signature am using to upload is
https://api-content.dropbox.com/1/files_put/dropbox/test?oauth_consumer_key=twcek2m7cxtantc&oauth_signature_method=PLAINTEXT&oauth_token=918v4lxg2w23car&oauth_version=1.0&oauth_signature=fbs34nykryouuj1%26rbbprgh95tjzf22
using this am getting the error
{"error": "Call requires one of the following methods: PUT, POST, got GET!"}
please tell me anyone what to do for resolve this error.
public FileSystemInfo UploadFile(string root, string path, string file)
{
var uri = new Uri(new Uri(DropboxRestApi.ApiContentServer),
String.Format("files_put/{0}/{1}",
root, UpperCaseUrlEncode(path)));
var oauth = new OAuth();
//var requestUri = oauth.DownloadSignRequest(uri, _consumerKey, _consumerSecret, "POST", _accessToken);
var requestUri = oauth.SignRequest(uri, _consumerKey, _consumerSecret, _accessToken, "PUT");
var request = (HttpWebRequest) WebRequest.Create(requestUri);
request.Method = WebRequestMethods.Http.Post;
request.KeepAlive = true;
byte[] buffer;
using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
{
int length = (int) fileStream.Length;
buffer = new byte[length];
fileStream.Read(buffer, 0, length);
}
request.ContentLength = buffer.Length;
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(buffer, 0, buffer.Length);
}
// request.Method = "POST";
var response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var json = reader.ReadToEnd();
return ParseJson<FileSystemInfo>(json);
}
I made a mistaken in saving path of the file where i want to upload it.
Give the same file name for save in path.
that's all.
Related
I created ASP.NET core 6 API project and used JWT authentication for each API end point.
But while executing in some physical system works fine but some other physical system and server throws below error
The server committed a protocol violation. Section=ResponseStatusLine
Sample Code
var request = (HttpWebRequest)WebRequest.Create(endpoint);
var token = System.Threading.Tasks.Task.Run(async() => await new Token("URL", "username", "pwd"])).Result;
request.Headers.Add("Authorization", "Bearer " + token);
request.Method = "POST";
var postData = JsonConvert.SerializeObject(Details, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
var data = Encoding.ASCII.GetBytes(postData);
request.ContentType = "application/json";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var responses = (HttpWebResponse)request.GetResponse();
Sample code based on HTTP Client
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), endpoint))
{
string token = SalesOperationAPIToken("url", "usertest", "pwd");
request.Headers.TryAddWithoutValidation("accept", "*/*");
request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + token);
string json = JsonConvert.SerializeObject(Details);
request.Content = new StringContent(json);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = httpClient.SendAsync(request).Result;
var responseMessage = response.Content.ReadAsStringAsync().Result;
}
}
I am not sure what configuration need to be changed to get this worked in all system.
Thanks in advance.
I am trying to attach files (screenshots) to an Azure DevOps work item via a C# desktop app. I have managed to attach files, but they're not valid image files, which leads me to believe that I'm doing something wrong in uploading them.
From the documentation DevOps Create Attachment below is the section on the Request body of the API call, which is rather vague.
From a GitHub discussion this answer seems to suggest that I just upload the binary content directly, which is what I'm doing.
My code is as follows
var img = File.ReadAllBytes(fname);
string query = #"/_apis/wit/attachments?fileName=" + fname + #"&api-version=6.0"
string response = AzureUtils.AttachFile(query, img, "POST", false, "application/octet-stream");
Is it correct that I literally pass in the byte array which is read from the file (variable img) as the body?
Why is it not a valid file when I look at it in DevOps?
The code for AttachFile is
public static string AttachFile(string query, byte[] data = null, string method = "GET",
bool dontUseBaseURL = false, string contentType = "application/json-patch+json")
{
try
{
HttpWebRequest request = WebRequest.Create(query) as HttpWebRequest;
request.ContentType = contentType;
request.Method = method;
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
request.Headers.Add("Authorization", "Basic " +
Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{1}", ["AzurePAT"]))));
if (data != null)
{
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(data);
}
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
request = null;
response = null;
return result;
}
I have a task which I need to upload a pdf converted to base64 string to Http post. I tried it using refit before but I failed to upload it. Now, I am trying a difference approach.
I used the web request POST method, First I converted the PDF to base64 but on the part that I call the stream.write method, I'm having an error since the file is already converted to base64 string and the stream.write paramater is byte array.
Also, how can I add these to the body using web request?
"mime": "application/pdf",
"data": "base64-data="
string pdfBase64;
const string pdfFileName = "file.pdf";
using (var pdfStream = await FileSystem.OpenAppPackageFileAsync(pdfFileName))
{
using (var pdfReader = new StreamReader(pdfStream))
{
var fileContents = await pdfReader.ReadToEndAsync();
pdfBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(fileContents));
}
}
WebRequest request = WebRequest.Create("https://goodmorning-axa-dev.azure-api.net/upload");
request.Method = "POST";
request.ContentLength = pdfBase64.Length;
request.ContentType = "application/json";
request.Headers.Add("x-axa-api-key", apiKey);
Stream stream = request.GetRequestStream();
stream.Write(pdfBase64, 0, pdfBase64.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
Toast.MakeText(this, sr.ReadToEnd(), ToastLength.Short).Show();
sr.Close();
stream.Close();
I am provided a webservice url similar to:
http://ericdev35:7280/persons/persons/
and a username and password.
I want to make a post call on this web service from WPF application.
The data to be sent to the service is the first name and last name of a person in the format:
"fname=Abc&lname=Xyz"
How can I make a call for this in C#?
Here is the code that I have tried:
HttpWebRequest httpWebRequest = (HttpWebRequest) WebRequest.Create("http://ericdev35:7280/persons/persons/");
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Credentials = new NetworkCredential(username, password);
string data = "fname=Abc&lname=Xyz";
StreamWriter writer = new StreamWriter(httpWebRequest.GetRequestStream());
writer.Write(data);
writer.Close();
This does not give me any error but I cannot see the data that I have posted. Is there anything that needs to be corrected?
Is the Content Type correct?
This Method posts json.
After that it gets the response and deserialize the Json Object.
private static string PostJson<T1>(string p_url, string p_json, string p_method, out T1 p_target)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(p_url);
httpWebRequest.UseDefaultCredentials = true;
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = p_method;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(p_json);
streamWriter.Flush();
streamWriter.Close();
}
HttpWebResponse httpResponse;
try
{
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
}
catch (WebException ex)
{
httpResponse = ex.Response as HttpWebResponse;
}
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var a_result = streamReader.ReadToEnd();
//If you dont need a Json object delete anything behind here
try
{
p_target = JsonConvert.DeserializeObject<T1>(a_result);
}
catch { p_target = default(T1); }
return a_result;
}
}
How do I post GZip data using RestSharp. I have the following code but it isn't working as I would expect:
var restRequest = new RestRequest(url, Method.POST)
{
Timeout = Constants.DefaultTimeoutMilliseconds
};
var dataStream = new MemoryStream();
using (var zipStream = new GZipStream(dataStream, CompressionMode.Compress))
{
using (var writer = new StreamWriter(zipStream))
{
writer.Write(new DotNetXmlSerializer().Serialize(content));
}
}
var compressedBytes = dataStream.ToArray();
restRequest.AddParameter("application/x-gzip", compressedBytes, ParameterType.RequestBody);
return _restClient.Execute<TResponseData>(restRequest);
When I run this and check the wireshark trace, the compressedBytes variable is posted as
'System.Byte[]' - as if ToString() has been called on it despite the parameter being a system.object.
If I pass the compressed byte array through as a string using both Convert.ToBase64String() and Encoding.Utf8.GetString() then I am unable to decompress the GZip at the server. I simply get 'System.IO.InvalidDataException: The magic number in GZip header is not correct. Make sure you are passing in a GZip'.
Is there any way of posting Gzipped data using RestSharp?
Make sure you've updated to the latest version of RestSharp (like 104.4.0) as this was a bug in a previous version.
I think this was fixed in 104.2 where the PUT or POST of binary data ended up with the System.Byte[] being represented as the string.
Update your NuGet reference and try it again. Good luck!
var body = "some string";
var dataStream = new MemoryStream();
byte[] dataToCompress = Encoding.UTF8.GetBytes(body);
using (var memoryStream = new MemoryStream())
{
using (var gzipStream = new GZipStream(memoryStream, CompressionLevel.Optimal))
{
gzipStream.Write(dataToCompress, 0, dataToCompress.Length);
}
dataStream = memoryStream;
}
var client = new RestClient("url");
var request = new RestRequest("", Method.POST);
var compressedBytes = dataStream.ToArray();
request.AddHeader("Content-Encoding", "gzip");
request.AddParameter("application/x-gzip", compressedBytes, ParameterType.RequestBody);
//client.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
IRestResponse response = await client.ExecuteAsync(request);
Console.WriteLine(response.Content);