I'm trying to insert Data from a Windows Phone App into a Database using a php script.
This is my C# code I execute when clicking on a button.
var request = WebRequest.Create(new Uri("xxx/Insert.php")) as HttpWebRequest;
request.Method = "POST";
string postdata = "Title=test&CategoryID=1";
byte[] data = Encoding.UTF8.GetBytes(postdata);
using (var requestStream = await Task<Stream>.Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, request))
{
await requestStream.WriteAsync(data, 0, data.Length);
}
I get the variable in the php script with
<?php
$title = $_POST["Title"];
$categoryID = $_POST["CategoryID"];
...
?>
Someone had the same problem here, but the solution didn't work, because
1.) WebClient is not available for WP8
2.) The second solution throws an Exception in App.i.g.cs at the line global::System.Diagnostics.Debugger.Break()
The problem is simply nothing happens. Has anybody encountered with the same problem?
I solved the Problem using System.Net.Http.HttpClient and System.Net.Http.FormUrlEncodedContent.
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("baseUrl.net");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("Title", "test")
});
var result = await client.PostAsync("/insert.php", content);
string resultContent = "result: "+result.Content.ReadAsStringAsync().Result;
EDIT: awaiting the PostAsync of the client
Related
Hi I am Calling External Rest API, I have Get Correct Results of GET and One POST API Result But this gives the error: The remote server returned an error: (400) Bad Request . But in POSTMAN it is working fine.
In Postman I am Calling http://192.168.x.x:8088/ari/channels/100001.100/play?media=sound:hello-world&api_key=admin:admin&app=myapp1 .
My Code is below and I passing Parameters and query string in API.
I think my problem is in media = sound:hello-world but I have no idea to solve.
string url = String.Format("http://192.168.x.x:8088/ari/channels/play?api_key=admin:admin");
WebRequest requestPost = WebRequest.Create(url);
requestPost.Method = "POST";
requestPost.ContentType = "application/json";
string postData = "{\"channelId\":\"100001.100\",\"media=sound\":\"hello-world\",\"app\":\"myapp1\"}";
using (var streamWriter = new StreamWriter(requestPost.GetRequestStream()))
{
streamWriter.Write(postData);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = requestPost.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var res = streamReader.ReadToEnd();
}
I have been trying to hit a Web controller directly to upload csv files using Nunit, Specflow and Restsharp but the tests are failing in groups but passes when individually. Another thing which we noticed is these are working fine locally as in running the app as localhost but not in other env. All other test groups are passing in that env. I have seen couple of posts which suggested not to use static properties to store values but i have tried that as well. we also added delay between threads but thats not working either
please can anyone help on this one or anyone who have faced this?
The error I am getting is timeout. if you accces it from the browser then there are no issues
I am using context injection to pass values from one another in step def file.
Here is what the code looks like
public (IRestResponse response,string RVtoken) GetRVtoken()
{
var client = new RestClient(ConfigurationManager.AppSettings["Web_URL"] +"Account/SignIn");
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
var html = new HtmlDocument();
html.LoadHtml(response.Content.ToString());
var RVtoken = html.DocumentNode.SelectSingleNode("/html[1]/body[1]/div[1]/div[1]/form[1]/input[1]/#value[1]").Attributes["value"].Value;
return (response, RVtoken);
}
public (CookieContainer cookieContainer, Uri target) GetAspxAuthToken(string email,string password, IRestResponse SignInResponse, string RVtoken)
{
string ReturnUrl = ConfigurationManager.AppSettings["Web_URL"] + "Account/SignIn?ReturnUrl=%2F";
var client = new RestClient(ReturnUrl);
CookieContainer cookieContainer = new CookieContainer();
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(ReturnUrl);
httpRequest.CookieContainer = cookieContainer;
httpRequest.Method = Method.POST.ToString();
string postData = string.Format("Email={0}&Password={1}&__RequestVerificationToken={2}&RememberMe=false", email, password, RVtoken);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.ContentLength = byteArray.Length;
Uri target = new Uri(ReturnUrl);
httpRequest.CookieContainer.Add(new Cookie(SignInResponse.Cookies[0].Name, SignInResponse.Cookies[0].Value) { Domain = target.Host });
httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
Stream dataStream = httpRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
HttpWebResponse myresponse = (HttpWebResponse)httpRequest.GetResponse();
return (cookieContainer,target);
}
public IRestResponse Uploadflex(string flexType,string filepath,IRestResponse SignInResponse)
{
RestClient newclient = newclient = new RestClient(ConfigurationManager.AppSettings["Web_URL"] + "audiences/" + flexType + "/upload?utc=1580117555355");
var newrequests = new RestRequest(Method.POST);
newrequests.AddFile("targetAreaFile",filepath);
newrequests.AddCookie(SignInResponse.Cookies[0].Name, SignInResponse.Cookies[0].Value);
newrequests.AddCookie(User.cookieContainer.GetCookies(User.target)[".aspxauth"].Name.ToString(), User.cookieContainer.GetCookies(User.target)[".aspxauth"].Value.ToString());
newrequests.AddParameter("name", "targetAreaFile");
newrequests.AddParameter("Content-Type", "application/vnd.ms-excel");
newrequests.AddParameter("Content-Disposition", "form-data");
var response = newclient.Execute(newrequests);
return response;
}
ok, so the issue was I was creating differnet sessions for these tests but somehow cookies were not clearing so I put all the tests under same session and it works magically.
We have a created an API for the application which takes the image via POST request process it and sends the result in JSON format.
We tried calling API from different sources like python, postman app, c#. We can successfully call end point using python and postman app but with c# getting error
c# code [Not working]
byte[] img_data = System.IO.File.ReadAllBytes(#"file_path");
string url_ep = "http://ip:port/get";
Dictionary<string, byte[]> fl_image = new Dictionary<string, byte[]>();
fl_image.Add("image", img_data);
string data = JsonConvert.SerializeObject(fl_image);
var dataToSend = Encoding.UTF8.GetBytes(data);
var request = HttpWebRequest.Create(url_ep);
request.ContentType = "application/json";
request.ContentLength = dataToSend.Length;
request.Method = "POST";
request.GetRequestStream().Write(dataToSend, 0, dataToSend.Length);
var response = request.GetResponse();
System.IO.Stream dataStream = response.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
python code [working]
import requests
url = 'http://ip:port/get'
fl_image = {'image': open('file_path', 'rb')}
res = requests.post(url, files=fl_image)
print(res.json())
API Endpoint
from flask import Flask, request
import numpy as np
import cv2 as cv
#app.route('/get', methods = ['POST'])
def get_image():
if request.method == 'POST':
file = request.files['image']
# Read file
f = file.read()
# convert string of image data to uint8
f1 = np.fromstring(f, np.uint8)
# decode image
f2 = cv.imdecode(f1,cv.IMREAD_COLOR)
There are several issues with the way you are posting data from C#. The most relevant one is that you are trying to post a file as a JSON object, with file contents as string.
This cannot work: your python server is clearly expecting multipart/form-data as content-type.
I also strongly recommend you to use HttpClient and not the old HttpWebRequest class to send HTTP Requests.
var filePath = #"file_path";
var url = "http://ip:port/get";
using (var client = new HttpClient())
using (var content = new MultipartFormDataContent())
using (var fileStream = File.OpenRead(filePath))
{
var imageContent = new StreamContent(fileStream);
// NOTE: the line below is not required, but useful when you know the media type
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");
content.Add(imageContent, "image", Path.GetFileName(filePath));
var response = await client.PostAsync(url, content);
var stringResponse = await response.Content.ReadAsStringAsync();
// do what you need with the response
}
Other minor issues:
Do not read the entire file in memory (using File.ReadAllBytes), but open a stream for reading instead.
Use async/await when possible, do not block on async code (do not use .Result, .Wait() or .GetAwaiter().GetResult() on Task or Task<T>)
Always call Dispose() on IDisposable objects when you have finished using them (wrapping them inside a using block)
You need to dispose the connections
reader.Close();
dataStream.Close();
response.Close();
Hope this helps
Or try using HttpClient for .net within the using block
I'm trying to do a WebRequest to a site from a Windows Phone Application.
But is vry important for me to also get the response from the server.
Here is my code:
Uri requestUri = new Uri(string.Format("http://localhost:8099/hello/{0}", metodo));
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.ContentType = "application/xml; charset=utf-8";
httpWebRequest.Method = "POST";
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
httpWebRequest.EndGetRequestStream, null))
{
string xml = "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">Ahri</string>";
byte[] xmlAsBytes = Encoding.UTF8.GetBytes(xml);
await stream.WriteAsync(xmlAsBytes, 0, xmlAsBytes.Length);
}
Unfortunatelly, I have no idea of how I could get the response from the server.
Does anyone have an idea?
Thanks in advance.
Thanks to #max I found the solution and wanted to share it above.
Here is how my code looks like:
string xml = "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">Claor</string>";
Uri requestUri = new Uri(string.Format("http://localhost:8099/hello/{0}", metodo));
string responseFromServer = "no response";
HttpWebRequest httpWebRequest = HttpWebRequest.Create(requestUri) as HttpWebRequest;
httpWebRequest.ContentType = "application/xml; charset=utf-8";
httpWebRequest.Method = "POST";
using (Stream requestStream = await httpWebRequest.GetRequestStreamAsync())
{
byte[] xmlAsBytes = Encoding.UTF8.GetBytes(xml);
await requestStream.WriteAsync(xmlAsBytes, 0, xmlAsBytes.Length);
}
WebResponse webResponse = await httpWebRequest.GetResponseAsync();
using (var reader = new StreamReader(webResponse.GetResponseStream()))
{
responseFromServer = reader.ReadToEnd();
}
I hope it will help someone in the future.
This is very common question for people new in windows phone app
development. There are several sites which gives tutorials for the
same but I would want to give small answer here.
In windows phone 8 xaml/runtime you can do it by using HttpWebRequest or a WebClient.
Basically WebClient is a wraper around HttpWebRequest.
If you have a small request to make then user HttpWebRequest. It goes like this
HttpWebRequest request = HttpWebRequest.Create(requestURI) as HttpWebRequest;
WebResponse response = await request.GetResponseAsync();
using (var reader = new StreamReader(response.GetResponseStream()))
{
string responseContent = reader.ReadToEnd();
// Do anything with you content. Convert it to xml, json or anything.
}
Although this is a get request and i see that you want to do a post request, you have to modify a few steps to achieve that.
Visit this place for post request.
If you want windows phone tutorials, you can go here. He writes awesome tuts.
I'm trying to migrate a Windows C# library to Windows Phone 8 and I'm forced to make some changes in how the library gets data from an online URI.
I'm using the BCL's HttpClient to perform my data retrieval and everything's fine for now.
The library also requires an upload feature, and I can't find a way to do this using th HttpClient.
Here's the code:
// Client setup
var httpclient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, string.Format(SubmitURI, value));
// Add the headers
request.Headers.Add("header", header);
var postData = GetPostData();
var data = Encoding.UTF8.GetBytes(postData);
// Side question -> Content is null here!
request.Content.Headers.Add("ContentType", "multipart/form-data; boundary=" + Boundary);
// BEGIN ORIGINAL CODE
var stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
// END ORIGINAL CODE
// Get response
var response = await httpclient.SendAsync(request);
var responseContent = new StreamReader(await response.Content.ReadAsStreamAsync()).ReadToEnd();
Between the BEGIN ORIGINAL CODE and END ORIGINAL CODE comments, there's the code that I'm not able to migrate, so that you can understand what it does and I may need to make it work on WP.
The other of the code is already working on WP, except for the
request.Content.Headers.Add("ContentType", "multipart/form-data; boundary=" + Boundary);
because, for some reasons, request.Content is null.
So my question is: how can I migrate those 3 lines to WP using HttpClient (or any better way)?
And, as a little side question, why is request.Content null?
EDIT: based on #Johan van der Slikke's answer I've edited my code. It compiles, but the server reports that no file was uploaded, so I guess that there are still some issues.
var stream = new MemoryStream(data);
var streamContent = new StreamContent(stream);
request.Content = streamContent;
request.Content.Headers.Add("ContentType", "multipart/form-data; boundary=" + Boundary);
// Get response
var response = await httpclient.SendAsync(request);
You should wrap your stream in the StreamContent class (a subclass of HttpContent) and send it with the HttpClient using the PostAsync or PutAsync methods.
Edit
You don't need to use HttpRequestMessage.
var stream = new MemoryStream(data);
var streamContent = new StreamContent(stream);
// Get response
var response = await httpclient.PostAsync(streamContent)
Also you don't need to create a MemoryStream with your byte array. You can wrap it in a ByteArrayContent directly.
var response = await httpclient.PostAsync(new ByteArrayContent(data))
Maybe (because I see you using multipart/form-data header) you should use MultipartFormDataContent classes or FormUrlEncodedContentClasses.
You can send multi-part content like this,
var client = new HttpClient();
var content = new MultipartContent();
content.Add(new ByteArrayContent(data));
var response = await client.PostAsync(SubmitUrl, content);
However, I am curious what media type your "PostData" is. You may want to set the content-type header on the ByteArrayContent.