Send and Rcived Image from Json webservice error: NotFound - json

I have create a jSON web service to save profile data with image. my service work properly but when send data to service HttpWebRequest return "The remote server returned an error: NotFound."
My code is this
void SendPost()
{
string webServiceAddress = #"http://localhost:51018/AMFDecember/WebService.asmx";
string methodName = "Register";
string url = string.Format("{0}/{1}", webServiceAddress, methodName);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackx), webRequest);
}
void GetRequestStreamCallbackx(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
StreamReader streamReader = new StreamReader(postStream);
string Response = streamReader.ReadToEnd();
string img="";
try
{
string img = Convert.ToBase64String(imageBytes);
}
catch { }
// Create the post data
string postData = "";
// <emailID>string</emailID>
//<pwd>string</pwd>
//<name>string</name>
//<img>base64Binary</img>
postData = "emailID=pr#pr.pr&pwd=1234&name=test&img=" + Convert.ToBase64String(imageBytes) + "";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
try
{
postStream.Write(byteArray, 0, byteArray.Length);
}
catch { }
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
string Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch (WebException e)
{
// Error treatment
// ...
}
}

I think your problem might be "http://localhost" - this means the service should be on localhost - i.e. within your phone?
Maybe try using the network ip address of your PC instead - you might need to use full IIS or IISExpress to host your service for this.

Related

Indexing in Elasticsearch

I am having problems indexing in elasticsearch. I have a function which creates an index and another one that creates a type mapping for a json I will be indexing. Both of these work fine but when I try calling the function to index something, it gives me a WebException saying that the remote server returned an error: (503) Server Unavailable. Any help will be greatly appreciated! Thanks!
This is my code:
public static void Main(string[] args)
{
string endpoint = "http://localhost:9200";
string index = "logs";
string type = "activity-log";
createIndex(endpoint, index);
createMapping(endpoint, index, type);
indexEvent(endpoint, index, type);
}
public static void createIndex(string endpoint, string index)
{
//Build request url
WebRequest request = WebRequest.Create(string.Format("{0}/{1}/", endpoint, index));
request.ContentType = "application/json"; //set content type of json
request.Method = "PUT"; //use POST method when creating an index
string json = "{\"settings\":{\"number_of_shards\":3,\"number_of_replicas\":2}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
string result = System.Convert.ToBase64String(byteData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteData, 0, byteData.Length);
dataStream.Close();
//create a web response
WebResponse response = request.GetResponse();
StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
Console.WriteLine(sr.ReadToEnd().Trim());
Console.ReadKey();
response.Close();
}
public static void createMapping(string endpoint, string index, string type)
{
//Build request url
WebRequest request = WebRequest.Create(string.Format("{0}/{1}/{2}/_mapping", endpoint, index, type));
request.ContentType = "application/json"; //set content type of json
request.Method = "PUT"; //use POST method when creating an index
string json = "{\"activitylogevent\":{\"properties\":{\"id\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"parentId\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"event\":{\"type\":\"string\",\"index\":\"not_analyzed\"}}}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
string result = System.Convert.ToBase64String(byteData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteData, 0, byteData.Length);
dataStream.Close();
//create a web response
WebResponse response = request.GetResponse();
StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
Console.WriteLine(sr.ReadToEnd().Trim());
Console.ReadKey();
response.Close();
}
public static void indexEvent(string endpoint, string index, string type)
{
//build the request URL
WebRequest request = WebRequest.Create(string.Format("{0}/{1}/{2}/", endpoint, index, type);
request.ContentType = "application/json"; //set content type of json
request.Method = "POST"; //use POST method when indexing a record without specifying id, and PUT when you specify an id
string jsonEvent = "{\"id\":\"123546789\",\"parentId\":\"abc123\",\"event\":\"CloseAccount\"}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
string result = System.Convert.ToBase64String(byteData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteData, 0, byteData.Length);
dataStream.Close();
//create a web response
WebResponse response = request.GetResponse();
Console.WriteLine("after get response");
Console.ReadLine();
StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
Console.WriteLine(sr.ReadToEnd().Trim());
Console.ReadKey();
response.Close();
}
I was doing something wrong in my createIndex function but here is my working function incase anyone finds it helpful:
public static void createIndex(string endpoint, string index)
{
//Build request url
WebRequest request = WebRequest.Create(string.Format("{0}/{1}/", endpoint, index));
request.ContentType = "application/json"; //set content type of json
request.Method = "PUT"; //use PUT method when creating an index
string json = "{\"settings\":{\"activity-log-events\":{\"number_of_shards\":3,\"number_of_replicas\":2}}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
string result = System.Convert.ToBase64String(byteData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteData, 0, byteData.Length);
dataStream.Close();
//create a web response
WebResponse response = request.GetResponse();
StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
Console.WriteLine(sr.ReadToEnd().Trim());
Console.ReadKey();
response.Close();
}
You have at least one error in your indexEvent() function. You are setting the string jsonEvent but then using an undefined string json when setting up byteData:
string jsonEvent = "{\"id\":\"123546789\",\"parentId\":\"abc123\",\"event\":\"CloseAccount\"}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
You'll note that you are doing this correctly in the other two functions, using the string json in both places. From createIndex:
string json = "{\"settings\":{\"number_of_shards\":3,\"number_of_replicas\":2}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
and from createMapping:
string json = "{\"activitylogevent\":{\"properties\":{\"id\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"parentId\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"event\":{\"type\":\"string\",\"index\":\"not_analyzed\"}}}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
There may be other things wrong in the code but that's definitely not going to work.
I made a some changes to my createIndex function and it worked. I posted the changes above.

how to handle http 400 and 401 error while using webclient to download JSON

I am using an api that returns an error 400 if URL is invalid and error 401 if daily qouta is exhausted by 50%. it also returns the json but am not able to download this json as an exception occurs if these error occurs. the api am using is
http://www.sharedcount.com/documentation.php
the code am using write now is...
private void _download_serialized_json_data(Uri Url)
{
var webClient = new WebClient();
var json_data = string.Empty;
// attempt to download JSON data as a string
try
{
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(Url);
}
catch (Exception) { }
}
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
String Json = null;
try
{
Json = e.Result;
}
catch (Exception ex)
{
}
if(Json!=null)
{
data=JsonConvert.DeserializeObject<RootObject>(Json);
result.Text = "facebook : "+data.Facebook.like_count+"\nGooglePlus : "+data.GooglePlusOne;
}
else
{
result.Text = "Invald URL \nor you exceeded your daily quota of 100,000 queries by 50%.";
}
}
currently am showing both errors if exception occurs. but i want to download the json and display that. how should i do that
To get the response content, you will need to use System.Net.Http.HttpClient instead. Install it from here: Microsoft HTTP Client Libraries
Then try this:
private async void Foo2()
{
Uri uri = new Uri("http://localhost/fooooo");
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.GetAsync(uri);
HttpStatusCode statusCode = response.StatusCode; // E.g.: 404
string reason = response.ReasonPhrase; // E.g.: Not Found
string jsonString = await response.Content.ReadAsStringAsync(); // The response content.
}
You can try something like this,
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
String Json = null;
if(e.Error != null)
{
//Some error occured, show the error message
var ErrorMsg = e.Error.Message;
}
else
{
//Got some response .. rest of your code
Json = e.Result;
}
}
I ran into this same issue using WebClient, I saw the error response stream being captured in Fiddler, but my .NET code was catching the exception and did not appear to be capturing the response stream.
You can read the Response stream from the WebException object to get the response data stream out.
using (System.Net.WebClient client = new System.Net.WebClient())
{
string response = "";
try
{
response = client.UploadString(someURL, "user=billy&pass=12345");
}
catch(WebException ex)
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(ex.Response.GetResponseStream()))
{
string exResponse = sr.ReadToEnd();
Console.WriteLine(exResponse);
}
}
}

I can't login to website using httpwebrequest

I'm trying login to website(example: https://www.facebook.com/login.php?login_attempt=1) using httpwebrequest by POST. But It's not return result after login.
I don't know what is wrong with my code, can you help me? Thanks so much!
This is my code:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
System.Uri myUri = new System.Uri("https://www.facebook.com/login.php?login_attempt=1");
HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(myUri);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
}
void GetRequestStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
// End the stream request operation
Stream postStream = myRequest.EndGetRequestStream(callbackResult);
StringBuilder postData = new StringBuilder();
postData.Append("email=myEmail");
postData.Append("&password=myPassword");
byte[] byteArray = Encoding.UTF8.GetBytes(postData.ToString());
postStream.Write(byteArray, 0, postData.Length);
postStream.Close();
myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
}
void GetResponsetStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
{
string result = httpWebStreamReader.ReadToEnd();
//For debug: show results
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// something do
});
}
}
I had just a quick look: https://www.facebook.com/login.php 's input fields are named "email" and "pass" (not "password").
Untested: Change
postData.Append("&password=myPassword");
to
postData.Append("&pass=myPassword");
Even if this works, I doubt that you get much further with whatever you intend to do. I recommend using one of the Facebook SDKs.

Handle httpWebRequest response

I've never been good in httpWebRequest. Always preferred WebClient but... desperate time, desperate measures.
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
//allDone.Set();
}
catch (WebException exception)
{
}
}
I can see (when I put breakpoint next) that responseString is beautiul JSON but I can't print it out (MessageBox etc) as my app will break.
Could you tell me how to handle that?
Cheers
Added magic
Dispatcher.BeginInvoke(() => { MessageBox.Show("OK"); });
And worked like a charm :)
Try this one
using System.Net;
public void sendRequest()
{
WebRequest webRequest;
webRequest = WebRequest.Create(XXXXXXXXXX);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.BeginGetRequestStream(newAsyncCallback(GetRequestStreamCallback), webRequest);
}
public void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
string postData = "Test";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
public void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
if (Response == "")
{
//show some error msg to the user
}
else
{
//Your response will be available in "Response"
}
}
catch (WebException)
{
//error
}
}
here the XXXXXXXX means your url with data which is sent to the server.

web service call in windows phone 8

I have a webservice written in java. I called from iPhone application but do not know how to call form windows phone. Web service have three parameter username, password and application id. I want to call through HttpWebRequest and receive response. How I can I do this ?
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
>
-<SOAP-ENV:Body>
-<doLogin xmlns="http://login.mss.uks.com">
-<loginid xsi:type="xsd:string">abc</loginid>
-<password xsi:type="xsd:string">pqrs</password>
-<app_id xsi:type="xsd:int">2</app_id>
</doLogin>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Thanks in advance.
If you have a proper web service sitting somewhere, you can use Visual Studio to generate wrapper code to access the web service. Check out this link to find how.
I've been struggling with this topic these days too. Here is my situation and how I solved this problem:
Problem
I've created a Web service using PHP with NuSOAP, and now I have to create a Windows Phone 8 App that consumes the Web service to do some stuff.
Solution
I going explain my solution using en example.
Here is the Web service:
<?php
require_once 'lib/nusoap.php';
function test()
{
return "Hello World!";
}
$server = new soap_server();
$server->configureWSDL("MyService", "urn:MyService");
// IMPORTANT: Avoid some ProtocolException
$server->soap_defencoding = 'utf-8';
$server->register('test',
array(),
array('greeting' => 'xsd:string'),
'Service',
false,
'rpc',
'literal', // IMPORTANT: 'encoded' isn't compatible with Silverlight
'A simple hello world'
);
if (isset($HTTP_RAW_POST_DATA)) {
$server->service($HTTP_RAW_POST_DATA);
} else {
$server->service("php://input");
}
?>
Now the client App in Windows Phone:
Create a new project.
Create a TextBox with name 'testText' and a Button with name 'testButton'.
Add a service reference
Solution Explorer -> MyProjectName -> Add Service Reference.
NOTE: If the Web service is mounted in your local computer, don't use 'localhost' as the name of the server, use your IP. In WP 8, 'localhost' refers to the device itself, not your computer. More info.
With this, Visual Studio will create automatically all the needed classes to use the Web service.
Add some action to the button:
private void testButton_Click(object sender, RoutedEventArgs e)
{
var client = new ServiceReference.MyServicePortTypeClient();
client.testCompleted += client_testCompleted;
client.testAsync();
}
private void client_testCompleted(object sender, ServiceReference.testCompletedEventArgs e)
{
testText.Text = e.Result;
}
Here is the result:
I hope this be useful.
Hope this will help you.
private void Button_Click_1(object sender, RoutedEventArgs e)
{
// Create a new HttpWebRequest object.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.xxx.com/webservicelogin/webservice.asmx/ReadTotalOutstandingInvoice");
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; Touch)";
request.CookieContainer = cookie;
// Set the Method property to 'POST' to post data to the URI.
request.Method = "POST";
// start the asynchronous operation
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
Stream postStream = request.EndGetRequestStream(asynchronousResult);
//postData value
string postData = "xxxxxxxxxx";
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Write to the request stream.
postStream.Write(byteArray, 0, postData.Length);
postStream.Close();
// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string read = streamRead.ReadToEnd();
//respond from httpRequest
TextBox.Text = read;
// Close the stream object
streamResponse.Close();
streamRead.Close();
response.Close();
}
Finally I got my perfect answer. By using the below code I solve my problem using HttpWebRequest.
string url = "http://urlname";
HttpWebRequest request = WebRequest.CreateHttp(new Uri(url)) as HttpWebRequest;
request.AllowReadStreamBuffering = true;
string strsoaprequestbody = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<soap-env:envelope xmlns:soap-env=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:soap-enc=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsi=\"http://www.w3.org/2001/xmlschema-instance\" xmlns:xsd=\"http://www.w3.org/2001/xmlschema\" soap-env:encodingstyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n" +
"<soap-env:body>\n" +
"<dologin xmlns=\"http://login.mss.uks.com\">\n" +
"<username xsi:type=\"xsd:string\">userID</username>\n" +
"<password xsi:type=\"xsd:string\">password</password>\n" +
"<app_id xsi:type=\"xsd:int\">2</app_id>\n" +
"</dologin>" +
"</soap-env:body>\n" +
"</soap-env:envelope>\n";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; Touch)";
request.Headers["SOAPAction"] = "http://schemas.xmlsoap.org/soap/encoding/";
// Set the Method property to 'POST' to post data to the URI.
request.Method = "POST";
request.ContentLength = strsoaprequestbody.Length;
// start the asynchronous operation
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
}
private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
Debug.WriteLine("GetRequestStreamCallback method called....");
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
Stream postStream = request.EndGetRequestStream(asynchronousResult);
string postData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n" +
"<SOAP-ENV:Body>\n" +
"<doLogin xmlns=\"http://login.mss.uks.com\">\n" +
"<username xsi:type=\"xsd:string\">userID</username>\n" +
"<password xsi:type=\"xsd:string\">password</password>\n" +
"<app_id xsi:type=\"xsd:int\">2</app_id>\n" +
"</doLogin>" +
"</SOAP-ENV:Body>\n" +
"</SOAP-ENV:Envelope>\n";
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Write to the request stream.
postStream.Write(byteArray, 0, postData.Length);
postStream.Close();
// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
Debug.WriteLine("GetResponseCallback method called....");
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
//display the web response
Debug.WriteLine("Response String : " + responseString);
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
catch (WebException ex)
{
using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream()))
{
Debug.WriteLine("Exception output : " + ex);
}
}
}