how to connect java servlet from c# windows form? - c#

I already have an existing application implemented using java in app engine....now i want to connect this servlet from c# forms program ?,...this is the tried out code for request
HttpWebRequest authRequest = (HttpWebRequest)HttpWebRequest.Create(googleLoginUrl);
byte[] buffer = Encoding.ASCII.GetBytes(postData);
authRequest.ContentLength = buffer.Length;
Stream postDataStr=authRequest.GetRequestStream();
postDataStr.Write(buffer, 0, buffer.Length);
postDataStr.Close();
now it is connected to the GSE(Google Servlet Engine)...i want a response for this....how to implement that?

You just need to read the response:
HttpWebResponse response = (HttpWebResponse)authRequest.GetResponse ();
Console.WriteLine ("Content length is {0}", response.ContentLength);
Console.WriteLine ("Content type is {0}", response.ContentType);
string raw_html = (new StreamReader(response.GetResponseStream()).ReadToEnd();
You can see further examples from: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse.aspx
Note: I believe since you're posting data you'll also have to set your authRequest as a POST via:
authRequest.Method = "POST";

Related

WebRequest timeout from Windows Service and Server

Currently we have a Windows Service which processes messages from RabbitMQ. It does this by using a web request to a URi. We then read the response and then proceed from there if it is successful.
Process Messages Method
//Deserialze the response
PMResponse res = (PMResponse)ser.ReadObject(GetResponse(addr + paramArgs));
GetResponse Method
private static MemoryStream GetResponse(string URi)
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(URi);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
//Console.WriteLine(responseFromServer);
MemoryStream mStrm = new MemoryStream(Encoding.UTF8.GetBytes(responseFromServer));
reader.Close();
dataStream.Close();
return mStrm;
}
The service is installed on one of our servers where, last week out of nowhere, the application stopped processing messages.
The web service we use to process the SMS messages works fine when we open the parameterised URL in the web browser.
The service also works on my local machine. However when deployed on the server either as a service or as a test console application the operation times out.
What problems do you think there are? The code works, just not on this server.
Answering to save people time:
"The problem is resolved, the company we use for sending the SMS restarted their servers and it worked fine. Many man hours wasted on this before it even got to me hah. Thanks for your time guys."

Vimeo uploading. Cannot get complete_uri field in response

I've been fiddling quite a bit with my uploading to vimeo.
I've made a ticket request.
I've uploaded the file.
I've checked the file if its uploaded.
I need to run the method DELETE with the complete_uri response i should get from my ticket.
However, im not receiving any complete_URI from the ticket response.
Here is my code:
public static dynamic GenerateTicket()
{
const string apiUrl = "https://api.vimeo.com/me/videos?type=streaming";
var req = (HttpWebRequest)WebRequest.Create(apiUrl);
req.Accept = "application/vnd.vimeo.*+json;version=3.0";
req.Headers.Add(HttpRequestHeader.Authorization, "bearer " + AccessToken);
req.Method = "POST";
var res = (HttpWebResponse)req.GetResponse();
var dataStream = res.GetResponseStream();
var reader = new StreamReader(dataStream);
var result = Json.Decode(reader.ReadToEnd());
return result;
}
This response gives me:
form
ticket_id
upload_link
upload_link_secure
uri
user
In order to finish my upload i need to run step 4 in this guide: https://developer.vimeo.com/api/upload
Sending parameter type=streaming as body:
ASCIIEncoding encoding = new ASCIIEncoding();
string stringData = "type=streaming"; //place body here
byte[] data = encoding.GetBytes(stringData);
req.Method = "PUT";
req.ContentLength = data.Length;
Stream newStream = req.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
At the moment, type=streaming must be sent in the body of the request, not as a url parameter.
This will probably change to allow either option.
the important point is :
"The first thing you need to do is request upload access for your application. You can do so from your My Apps page."
If you get all values without complete_uri, it means: you dont have an upload access token. So go to your apps and make an upload request

C# api responce and request

I currently have the code
try
{
string url = "http://myanimelist.net/api/animelist/update/" + "6.xml";
WebRequest request = WebRequest.Create(url);
request.ContentType = "xml/text";
request.Method = "POST";
request.Credentials = new NetworkCredential("username", "password");
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("<episode>4</episode>");
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();
MessageBox.Show("Updated");
}
catch (Exception s)
{
MessageBox.Show(s.Message);
}
I am trying do send data to myanimelist.net
The code they have written for is this
URL: http://myanimelist.net/api/animelist/update/id.xml
Formats: xml
HTTP Method(s): POST
Requires Authentication:true
Parameters:
id. Required. The id of the anime to update.
Example: http://myanimelist.net/api/animelist/update/21.xml
data. Required. A parameter specified as 'data' must be passed. It must contain anime values in XML format.
Response: 'Updated' or detailed error message.
The usage code example the have stated is this, does anyone know how to do this in c# or what was wrong with my original code?
Usage Examples:
CURL: curl -u user:password -d data="XML" http://myanimelist.net/api/animelist/update/21.xml
edit: When i lauch myanimelist.net it shows that it has not been updated, i am sure that my username and password credentials are correct
Edit 2 : I have now added a response which comes up with the error
"The remote server returned an error: (501) Not Implemented."
You're not actually performing the request, so once you're done writing to the request stream itself, perform the actual web request:
string result;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
}
Also, the content type should be text/xml or application/xml - the API may be complaining about that. Read the documentation for their API carefully and ensure what you're sending is correct.

HttpWebRequest POST Login error 405

Im trying to make a small login system but i have this problem that when the project runs on VS2010 it says :
The remote server returned an error: (405) Method Not Allowed.
Heres my code:
//Our URL
string uri = "https://************************/ValidateUsername";
//Our postvars
byte[] buffer = Encoding.ASCII.GetBytes( "username=user" );
//Initialization
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Accept = "application/json;odata=verbose";
request.Headers.Add("Language", "es-MX");
request.Headers.Add("Application", "-------------------");
request.Headers.Add("Version", "1.0");
//Our method is POST, otherway buffer would be useless
request.Method = "POST";
//We use form contentType, for the postvars
request.ContentType = "application/x-www-form-urlencoded";
//The lenght of the content its set by postvars (buffer) lenght
request.ContentLength = buffer.Length;
//We open a stream for writing the postvars
Stream PostData = request.GetRequestStream();
//Now we write, and afterwards, we close.
PostData.Write(buffer, 0, buffer.Length);
When i hover the pointer over "PostData" and then i go to the length and position attributes, i can read :
Length = 'PostData.Length' threw an exception of type 'System.NotSupportedException'
base {System.SystemException} = {"This stream does not support seek operations."}
im not sure if this is the real problem, but im trying to give the mos of information possible.
PostData.Close();
//Get the response Handle
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//lets show info about the response
Console.WriteLine("Estatus de la respuesta:" + response.StatusCode);
Console.WriteLine("Servidor : " + response.Server);
//Now we read the response (the string), and output it
//Stream answer = response.GetResponseStream();
//StreamReader _answer = new StreamReader(answer);
//Console.WriteLine("Respuesta: " + _answer.ReadToEnd());
At some forum i read that maybe the "_answer.ReadToEnd()" could be the problem but even thought i commented , the problem still arises.
Im doing this so i can try it later on windows phone, dont know if im wasting my time , because they are not related.
I hope someone can help. Thanks in advance.

HTTP POST in .NET doesn't work

I've got a problem with creating an HTTP post request in .NET. When I do this request in ruby it does work.
When doing the request in .NET I get following error:
<h1>FOXISAPI call failed</h1><p><b>Progid is:</b> carejobs.carejobs
<p><b>Method is:</b> importvacature/
<p><b>Parameters are:</b>
<p><b> parameters are:</b> vacature.deelnemernr=478
</b><p><b>GetIDsOfNames failed with err code 80020006: Unknown name.
</b>
Does anyone knows how to fix this?
Ruby:
require 'net/http'
url = URI.parse('http://www.carejobs.be/scripts/foxisapi.dll/carejobs.carejobs.importvacature')
post_args = {
'vacature.deelnemernr' => '478',
}
resp, data = Net::HTTP.post_form(url, post_args)
print resp
print data
C#:
Uri address = new Uri(url);
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// Create the data we want to send
StringBuilder data = new StringBuilder();
data.Append("vacature.deelnemernr=" + HttpUtility.UrlEncode("478"));
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
// Set the content length in the request headers
request.ContentLength = byteData.Length;
// Write data
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
result = reader.ReadToEnd();
}
return result;
Don't you need the ? after the URL in order to do a post with parameters? I think that Ruby hides this behind the scenes.
I found the problem! The url variable in the C# code was "http://www.carejobs.be/scripts/foxisapi.dll/carejobs.carejobs.importvacature/"
It had to be "http://www.carejobs.be/scripts/foxisapi.dll/carejobs.carejobs.importvacature" without the backslash.

Categories

Resources