I'm trying to get a Json string from an Url in a windows phone 8 application (the page requires an authentication and I think that's where my code is failing), I'm using the following code:
public WebClient client = new WebClient();
public string result;
public void DoStuff()
{
string username = "username";
string password = "password";
string url = "myurl";
client.Credentials = new NetworkCredential(username, password);
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
client.DownloadStringAsync(new Uri(url));
}
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
result = e.Result;
}
However, when run the app, I got a System.Reflection.TargetInvocationException at e.result
Going into InnerException I see this:
[System.Net.WebException] {System.Net.WebException: An exception
occurred during a WebClient request. --->
System.Net.ProtocolViolationException: A request with this method
cannot have a request body. at
System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback
beginMethod, Object state) at
System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult
asyncResult) at System.Net.WebClient.GetWebResponse(WebRequest
request, IAsyncResult result) at
System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)
--- End of inner exception stack trace ---} System.Net.WebException
I've tried with HttpClient but I got the same problem. I would like to know if somebody knows how to solve this.
Thanks!
UPDATE: I've tried navigating to the page on my phone using IE, and then the IE Mobile says: "Unsupported Address, IE Mobile doesn't support this type of address and can't display this page". That's why the app is crashing too?
GET Method (with/without Credentials)
private string username = "user";
private string password = "passkey";
private string myUrl = "http://some_url.com/id?=20";
private WebClient client = new WebClient();
private void retrieveJson()
{
client.Credentials = new NetworkCredential(username, password);
client.Encoding = Encoding.UTF8;
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
client.DownloadStringAsync(new Uri(myUrl), UriKind.Relative);
}
//WebClient String (json content) Download
private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
// You will get you Json Data here..
var myJSONData = e.Result;
JObject JsonData = JObject.Parse(myJSONData);
//Do something with json
//Ex: JsonData["Array1"][5]
}
POST Method (with/without Credentials)
private string username = "user";
private string password = "passkey";
private string myUrl = "http://some_url.com/id?=20";
private WebClient client = new WebClient();
private string parameters = "{\"I_NAME\":\"0000"\"}"; //Example
private void postMethod()
{
client.Credentials = new NetworkCredential(username, password);
client.Encoding = Encoding.UTF8;
client.Headers["Content-Length"] = parameters.Length.ToString();
client.UploadStringCompleted += new UploadStringCompletedEventHandler(client_UploadStringCompleted);
client.UploadStringAsync(new Uri(myUrl), "POST", parameters);
}
private void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
if (e.Error == null)
{
var myJSONData = e.Result;
JObject JsonData = JObject.Parse(myJSONData);
}
}
Related
I have via gupshup created a viber bot. I run my WebForm application with IIS server in win 10. I tried to send a message to my viberbot via api post method but c# strangle me.(I tested url and parameters with success)
here is my code :
protected void viber_msg(String viberid, String strmsg)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.gupshup.io/sm/api/bot/mybotname/msg?apikey=mykey");
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "context={'botname':'mybotname','channeltype':'viber','contextid':'viberid','contexttype':'p2p'}&message="+strmsg;
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
viber_msg("viberuserID", "This is a message");
}
The error I am getting is "System.Net.WebException: 'The remote server returned an error: (403) Forbidden.'"
Also tried with POSTMAN and getting "message": "Invalid authentication credentials"
Thnx in advance...
protected void viber_msg(String viberid, String message)
{
var client = new RestClient("https://api.gupshup.io/sm/api/bot/mybot/msg?apikey=myapikey");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("context", "{\"botname\": \"mybot\",\"channeltype\" :\"viber\",\"contextid\": \""+viberid+"\",\"contexttype\": \"p2p\"}");
request.AddParameter("message", message);
IRestResponse response = client.Execute(request);
}
protected void Button1_Click(object sender, EventArgs e)
{
viber_msg("viberid", "message");
}
}
RestSharp Library!!!
I want to do this thing in windows phone 8.1 please suggest how to do.I have tried httpclient but didn't achieve the same result please suggest me something
private async void Button_Click(object sender, RoutedEventArgs e)
{
WebClient web = new WebClient();
web.Headers["content-type"] = "application/x-www-form-urlencoded";
string arg = "id=" + newone.Text;
// var postdata =js
string arg1 = "id=" + newone.Text;
//web.UploadStringAsync(new Uri("http://terasol.in/hoo/test.php/?id=&ncuavfvlqfd"), "GET");
web.UploadStringAsync(new Uri("http://terasol.in/hoo/test.php"), "POST", arg1);
web.UploadStringCompleted += web_uploadstringcomplete;
}
void web_uploadstringcomplete(object sender, UploadStringCompletedEventArgs e)
{
MessageBox.Show(e.Result);
}
thank you
Based on your sample code, and running it,
using the following code, I get the same value returned.
private static void Button_Click2(string id)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://terasol.in/");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("id", id)
});
var result = client.PostAsync("/hoo/test.php", content).Result;
string resultContent = result.Content.ReadAsStringAsync().Result;
Console.WriteLine(resultContent);
}
}
I am trying to retrieve data from an authorization-restricted database which only contains text to my Windows Phone 8 app. My code looks like this:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
WebClient wc = new WebClient();
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
wc.Credentials = new NetworkCredential("username", "password");
wc.DownloadStringAsync(new Uri(#"http://www.siteaddress.com"));
}
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string text = e.Result;
}
Unfortunately I'm getting the following message. Am I doing anything wrong? Thanks in advance.
http://s30.postimg.org/yuc0mcb5t/pic.png
If you are trying to send data to the server to receive response from the server, then you mean POST data to server .
void GetPosts(string UserID)
{
WebClient webclient = new WebClient();
Uri uristring = new Uri("somelink.com");
webclient.Headers["Content-Type"] = "application/x-www-form-urlencoded";
string postJsonData = string.Empty;
postJsonData += "userId=" + UserID;//parameters you want to POST
webclient.UploadStringAsync(uristring, "POST", postJsonData);
webclient.UploadStringCompleted += webclient_UploadStringCompleted;
}
void webclient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
.... // any code
}
I'm developping on Windows phone 8 and I would like to know if it's possible to manipulate data in the same method when we call DownloadStringCompleted of WebClient?
private void DownloadDataFromWebService(String uri)
{
WebClient wc = new WebClient();
wc.DownloadStringAsync(new Uri(uri));
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
}
private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
RootObject r = JsonConvert.DeserializeObject<RootObject>(e.Result);
List<Category> listeCategories = r.Result;
}
Thus, I would like to manage all code in only one method because I would like to return an object
For example,
private List<Category> GetCategories(String uri)
{
WebClient wc = new WebClient();
wc.DownloadStringAsync(new Uri(uri));
.....
.....
RootObject r = JsonConvert.DeserializeObject<RootObject>(e.Result);
return (List<Category>) r.Result;
}
Yes, that is possible, due to magic TaskCompletionSource class, http://msdn.microsoft.com/en-us/library/dd449174(v=vs.95).aspx . To download:
async Task<List<object>> getCategories(String uri)
{
var taskCompletionObj = new TaskCompletionSource<string>();
var wc= new webClient();
wc.DownloadStringAsync(new URI(uri, Urikind.Absolute)) += (o, e) =>
{
taskCompletionObj.TrySetResult(e.Result);
};
string rawString = await taskCompletionObj.Task;
RootObject r = JsonConvert.DeserializeObject<RootObject>(rawString);
return (List<Category>)r.Result;
}
To use: var x = await getCategories(myURI);
I'm trying to get the html code of certain webpage,
I have a username and a password that are correct but i still can't get it to work,
this is my code:
private void buttondownloadfile_Click(object sender, EventArgs e)
{
NetworkCredentials nc = new NetworkCredentials("?", "?", "http://cdrs.globalpopsvoip.com/0000069/20091229/20091228_20091228.CDR");
WebClient client = new WebClient();
client.Credentials = nc;
String htmlCode = client.DownloadString("http://cdrs.globalpopsvoip.com/0000069/20091229/20091228_20091228.CDR");
MessageBox.Show(htmlCode);
}
The MessageBox is just to test it,
the problem is that every time I get to this line:
String htmlCode = client.DownloadString("http://cdrs.globalpopsvoip.com/0000069/20091229/20091228_20091228.CDR");
I get an exception:
The remote server returned an error:
(401) Unauthorized.
How do I fix this?
In my case client.UseDefaultCredentials = true; did the trick.
I have tried the following code and it is working.
private void Form1_Load(object sender, EventArgs e)
{
try
{
// Create Request
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(#"http://192.168.0.181/axis-cgi/com/ptz.cgi?move=up");
// Create Client
WebClient client = new WebClient();
// Assign Credentials
client.Credentials = new NetworkCredential("root", "a");
// Grab Data
string htmlCode = client.DownloadString(#"http://192.160.0.1/axis-cgi/com/ptz.cgi?move=up");
// Display Data
MessageBox.Show(htmlCode);
}
catch (WebException ex)
{
MessageBox.Show(ex.ToString());
}
}
Try to create a NetworkCredential without that domain part:
NetworkCredential nc = new NetworkCredential("?", "?");