I have a digital IP camera. It is preset to use set static IP address, and I have asked the manufacturer whether they have an API I can call to set it to DHCP.
They replied:
PUT /Network/interfaces/1/ipAddress HTTP/1.1
Authorization: Basic YWRtaW46MTIzNDU=
Content-Type:text/xml
Content-Length:387
<IPAddress version="1.0" xmlns="http://www.hikvision.com/ver10/XMLSchema">
<ipVersion>v4</ipVersion>
<addressingType>dynamic</addressingType>
<ipAddress>172.2.62.49</ipAddress>
<subnetMask>255.255.255.0</subnetMask>
<DefaultGateway>
<ipAddress>172.2.62.1</ipAddress>
</DefaultGateway>
<PrimaryDNS>
<ipAddress>0.0.0.0</ipAddress>
</PrimaryDNS>
</IPAddress>
So, I translated that to:
private void button1_Click(object sender, EventArgs e)
{
try
{
HttpWebRequest req = null;
WebResponse rsp = null;
string uri = "http://192.0.0.64/Network/interfaces/1/ipAddress";
req =(HttpWebRequest) WebRequest.Create(uri);
req.UseDefaultCredentials = true;
//req.Credentials = new NetworkCredential("admin", "12345"); //I have tried using this as well as these are the default admin/pw supplied
req.Method = "PUT";
req.ProtocolVersion = HttpVersion.Version11;
req.ContentLength = 387;
string _cred = string.Format("{0} {1}", "Basic", "YWRtaW46MTIzNDU=");
req.Headers[HttpRequestHeader.Authorization] = _cred;
req.ContentType = "text/xml";
StreamWriter writer = new StreamWriter(req.GetRequestStream());
writer.WriteLine(GetDHCPPost());
writer.Close();
rsp = req.GetResponse();
}
catch (Exception ex)
{
//errors here >> cannot connect to server
}
}
private string GetDHCPPost()
{
StringBuilder sb = new StringBuilder();
sb.Append("<IPAddress version=\"1.0\" xmlns=\"http://www.hikvision.com/ver10/XMLSchema\">");
sb.Append("<ipVersion>v4</ipVersion>");
sb.Append("<addressingType>dynamic</addressingType>");
sb.Append("<ipAddress>172.2.62.49</ipAddress>");
sb.Append("<subnetMask>255.255.255.0</subnetMask>");
sb.Append("<DefaultGateway>");
sb.Append("<ipAddress>172.2.62.1</ipAddress>");
sb.Append("</DefaultGateway>");
sb.Append("<PrimaryDNS>");
sb.Append("<ipAddress>0.0.0.0</ipAddress>");
sb.Append("</PrimaryDNS>");
sb.Append("</IPAddress> ");
return sb.ToString();
}
But does not work. Am I making an obvious error?
Try this.
If you're using admin/12345.
I made this to write the temperature overlay to my hikvision camera.
Your xml code is definitely correct. I'm not 100% you would need to declare the port number, I know I always had too.
SendToHikVision("admin", "12345", "192.0.0.64", "*The Port You're Using");
void SendToHikVision(string UserName, string Password, string IP, string Port)
{
try
{
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://" + IP + ":" + Port + "/Network/interfaces/1/");
wr.Accept = "*/*";
wr.Method = "PUT";
wr.ReadWriteTimeout = 5000;
wr.Credentials = new NetworkCredential(UserName, Password);
byte[] pBytes = GetDHCPPost();
wr.ContentLength = pBytes.Length;
using (Stream DS = wr.GetRequestStream())
{
DS.Write(pBytes, 0, pBytes.Length);
DS.Close();
}
wr.BeginGetResponse(r => { var reponse = wr.EndGetResponse(r); }, null);
}
catch { }
}
byte[] GetDHCPPost()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("<IPAddress version=\"1.0\" xmlns=\"http://www.hikvision.com/ver10/XMLSchema\">");
sb.AppendLine("<ipVersion>v4</ipVersion>");
sb.AppendLine("<addressingType>dynamic</addressingType>");
sb.AppendLine("<ipAddress>172.2.62.49</ipAddress>");
sb.AppendLine("<subnetMask>255.255.255.0</subnetMask>");
sb.AppendLine("<DefaultGateway>");
sb.AppendLine("<ipAddress>172.2.62.1</ipAddress>");
sb.AppendLine("</DefaultGateway>");
sb.AppendLine("<PrimaryDNS>");
sb.AppendLine("<ipAddress>0.0.0.0</ipAddress>");
sb.AppendLine("</PrimaryDNS>");
sb.AppendLine("</IPAddress> ");
return Encoding.ASCII.GetBytes(sb.ToString());
}
Related
I am trying to passing C# Web service Parameters to PHP Application but not getting below is my code. Actually I am passing username and password xml format because no buddy should not see that credential while passing.
Below is my C# Web service using asp.net web form button click to redirect PHP application.
[WebMethod]
public string POSTXml(string username, string password)
{
WebRequest req = null;
WebResponse rsp = null;
try
{
StringBuilder strRequest = new StringBuilder();
string url = "http://xyz.in/getuser.php/";
req = WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "text/xml";
StreamWriter writer = new StreamWriter(req.GetRequestStream());
writer.WriteLine(username,password);
writer.Close();
rsp = req.GetResponse();
var sr = new StreamReader(rsp.GetResponseStream());
string responseText = sr.ReadToEnd();
return responseText;
}
catch (Exception e)
{
throw new Exception("There was a problem sending the message");
}
}
Below is my button click code.
protected void Button2_Click(object sender, EventArgs e)
{
localhost.WebService objserv1 = new localhost.WebService();
Label.Text = objserv1.POSTXml("nagapavani", "tech#1234");
}
Actually when user will button click passing some values to web service and through web service want to pass that value to php application. Is there Other way to achieve that requirement. When I am going to button click not going to redirect and taken this code from google.
You could send the data as following. Convert it to a byte array and write it to the request stream:
[WebMethod]
public string POSTXml(string username, string password)
{
WebRequest req = null;
WebResponse rsp = null;
try
{
string data = "user=" + username + "&password=" + password;
string url = "http://xyz.in/getuser.php/";
byte[] buffer = Encoding.ASCII.GetBytes(data);
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
WebReq.Method = "POST";
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = buffer.Length;
using (Stream PostData = WebReq.GetRequestStream())
{
PostData.Write(buffer, 0, buffer.Length);
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
using (Stream stream = WebResp.GetResponseStream())
{
using (StreamReader strReader = new StreamReader(stream))
{
return strReader.ReadToEnd();
}
}
WebResp.Close();
}
}
catch (Exception e)
{
throw new Exception("There was a problem sending the message");
}
return String.Empty;
}
I have a client application which communicates to a central server through web services (python based web service). I am currently using post method to send data. This fails on certain systems while works on most other.
here is the code
//method with post
private bool sendDataToServicePost1 (string url,string data)
{
try
{
string boundary = Guid.NewGuid().ToString().Replace("-", "");
string newLine = "\r\n";
// create cookie
Cookie sessionCookie = new Cookie();
sessionCookie.HttpOnly = true;
sessionCookie.Domain = App.ServerIP;
sessionCookie.Name = "session_id";
sessionCookie.Value = App.SessionId;
// open HTTP web request
HttpWebRequest _webRequest = (HttpWebRequest)WebRequest.Create(url);
// add cookie to request
_webRequest.CookieContainer = new CookieContainer();
_webRequest.CookieContainer.Add(sessionCookie);
//setup POST params
_webRequest.Method = "POST";
_webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
_webRequest.Timeout = 600000;
MemoryStream ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms);
sw.Write(string.Format(sendFormat, boundary, newLine, "Data", data));
sw.Write("--{0}--{1}", boundary, newLine);
sw.Flush();
_webRequest.ContentLength = ms.Length;
Stream s = _webRequest.GetRequestStream();
ms.WriteTo(s);
ms.Flush();
ms.Close();
s.Close();
var _webResponse = RadWebRetry.ReTryGetWebResponse(_webRequest);
StreamReader _streamReader = new StreamReader(RadWebRetry.ReTryGetResponseStream(_webResponse));
string jsonFormattedResponse = _streamReader.ReadToEnd();
logger.Debug("The response from the save operation : " + jsonFormattedResponse);
}
catch (Exception excp)
{
logger.Fatal("Execption:{0}", excp.ToString());
return false;
}
}
When converting the post method to get it works fine.
//method with Get
private bool sendDataToServiceGet((string url,string data)
{
try
{
HttpWebResponse _webResponse = null;
string urlfull = url + "?Data=" + data;
HttpWebRequest _webRequest = (HttpWebRequest)WebRequest.Create(urlfull);
Cookie sessionCookie = new Cookie();
sessionCookie.HttpOnly = true;
sessionCookie.Domain = App.ServerIP;
sessionCookie.Name = "session_id";
sessionCookie.Value = App.SessionId;
_webRequest.CookieContainer = new CookieContainer();
_webRequest.CookieContainer.Add(sessionCookie);
_webRequest.Method = "GET";
_webResponse = RadWebRetry.ReTryGetWebResponse(_webRequest);
System.IO.StreamReader _streamReader = new System.IO.StreamReader(RadWebRetry.ReTryGetResponseStream(_webResponse));
string jsonFormattedResponse = _streamReader.ReadToEnd();
logger.Debug("The response from the save operation : " + jsonFormattedResponse);
}
catch (Exception excp)
{
logger.Fatal("Execption:{0}", excp.ToString());
return false;
}
}
According to me this exception should not be system related, but we are observing it in system to system basis.
I am encountering a problem getting the access_token in client application using oauth.
The returned response has empty body though in API I can see the response is not empty.
tokenresponse = {
"access_token":"[ACCESSTOKENVALUE]",
"token_type":"bearer",
"expires_in":"1200",
"refresh_token":"[REFRESHTOKENVALUE]",
"scope":"[SCOPEVALUE]"
}
The method from API that returns the token http://api.sample.com/OAuth/Token:
public ActionResult Token()
{
OutgoingWebResponse response =
this.AuthorizationServer.HandleTokenRequest(this.Request);
string tokenresponse = string.Format("Token({0})", response!=null?response.Body:""));
return response.AsActionResult();
}
The client method that requests the token is:
public string GetAuthorizationToken(string code)
{
string Url = ServerPath + "OAuth/Token";
string redirect_uri_encode = UrlEncode(ClientPath);
string param = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",code, ClientId, ClientSecret, redirect_uri_encode);
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;
request.Headers.Remove(HttpRequestHeader.Cookie);
var bs = Encoding.UTF8.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
var sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
if (!string.IsNullOrEmpty(result))
{
TokenData tokendata = JsonConvert.DeserializeObject<TokenData>(result);
return UpdateAuthorizotionFromToken(tokendata);
}
return null;
}
The result variable is empty.
Please let me know if you have any idea what could cause this. Initially I assumed is because of the cookies so I tried to remove them from request.
Thanks in advance.
Dear just create webclient using following code and you will get json info in tokeninfo.I used it and simply its working perfect.
WebClient client = new WebClient();
string postData = "client_id=" + ""
+ "&client_secret=" + ""
+ "&grant_type=password&username=" + "" //your username
+ "&password=" + "";//your password :)
string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
string tokenInfo = client.UploadString(soundCloudTokenRes, postData);
You can then use substring that contains only token from tokeninfo.
To upload tracks on sound cloud.
private void TestSoundCloudupload()
{
System.Net.ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create("https://api.soundcloud.com/tracks") as HttpWebRequest;
//some default headers
request.Accept = "*/*";
request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
request.Headers.Add("Accept-Language", "en-US,en;q=0.8,ru;q=0.6");
//file array
var files = new UploadFile[] { new UploadFile(Server.MapPath("Downloads//0.mp3"), "track[asset_data]", "application/octet-stream") };
//other form data
var form = new NameValueCollection();
form.Add("track[title]", "Some title");
form.Add("track[sharing]", "public");
form.Add("oauth_token", "");
form.Add("format", "json");
form.Add("Filename", "0.mp3");
form.Add("Upload", "Submit Query");
try
{
using (var response = HttpUploadHelper.Upload(request, files, form))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
Response.Write(reader.ReadToEnd());
}
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
The problem with this code is that the file, once it is uploaded, is not the correct format. I'm trying to upload a .zip file.
public string HttpPost(string uri, string parameter)
{
WebRequest webRequest = WebRequest.Create(uri);
NetworkCredential credentials = new NetworkCredential("username", "password");
webRequest.Credentials = credentials;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameter);
Stream os = null;
try
{ // send the Post
webRequest.ContentLength = bytes.Length; //Count bytes to send
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Send it
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Request error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (os != null)
{
os.Close();
}
}
try
{ // get the response
WebResponse webResponse = webRequest.GetResponse();
if (webResponse == null)
{ return null; }
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
return sr.ReadToEnd().Trim();
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Response error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return null;
}
This example how to upload file in MyBucket
private const string KeyId = "Your KeyId";
private const string AccessKey = "Your AccessKey";
private const string S3Url = "https://s3.amazonaws.com/";
private static void UploadFile()
{
var fileData = File.ReadAllBytes(#"C:\123.zip");
string timeStamp = string.Format("{0:r}", DateTime.UtcNow);
string stringToConvert = "PUT\n" + //Http verb
"\n" + //content-md5
"application/octet-stream\n" + //content-type
"\n" + //date
"x-amz-acl:public-read"+"\n" + //date
"x-amz-date:" + timeStamp + "\n" + //optionall
"/MyBucket/123.zip"; //resource
var ae = new UTF8Encoding();
var signature = new HMACSHA1 {Key = ae.GetBytes(AccessKey)};
var bytes = ae.GetBytes(stringToConvert);
var moreBytes = signature.ComputeHash(bytes);
var encodedCanonical = Convert.ToBase64String(moreBytes);
var url = "https://MyBucket.s3.amazonaws.com/123.zip";
var request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "PUT";
request.Headers["x-amz-date"] = timeStamp;
request.Headers["x-amz-acl"] = "public-read";
request.ContentType = "application/octet-stream";
request.ContentLength = fileData.Length;
request.Headers["Authorization"] = "AWS " + KeyId + ":" + encodedCanonical;
var requestStream = request.GetRequestStream();
requestStream.Write(fileData, 0, fileData.Length);
requestStream.Close();
using (var response = request.GetResponse() as HttpWebResponse)
{
var reader = new StreamReader(response.GetResponseStream());
var data = reader.ReadToEnd();
}
}
Take a look on Amazon S3 REST API
Request you to please help me to solve my problem. I am new to web-services and HTTP.
I wrote following code to update data to website. Code run; but I am not able to see my data if uploaded. Here we have facility to see what data is getting uploaded but I am not able to see my data.
// Above URL is not real as I do not want to disclose real URL as of Now
Uri targetUrl = new Uri("http://www.x86map.com/post-embed/ewspost");
HttpWebRequest request = null;
StringBuilder sb = new StringBuilder();
Stream requestStream = null;
try
{
request = (HttpWebRequest)WebRequest.Create(targetUrl);
using (StreamReader inputReader = new StreamReader("C:\\SupportXml.xml"))
{
sb.Append(inputReader.ReadToEnd());
}
String postData = sb.ToString();
byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postDataBytes.Length;
request.KeepAlive = true;
request.Accept = "*/*";
request.Headers.Add("Cache-Control", "no-cache");
request.Headers.Add("Accept-Language", "en-us");
request.Headers.Add("Accept-Encoding", "gzip,deflate");
request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8,q=0.66,*;q=0.66");
requestStream = request.GetRequestStream();
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
}
catch (Exception ex)
{
Console.Write(ex.ToString());
}
finally
{
if (null != requestStream)
requestStream.Close();
}
URL I mentioned in Code is not real. Please let me know what is the problem in my code.
Following is the Java code working perfect. I want to convert same code in C#.
// Above URL is not real as I do not want to disclose real URL as of Now
String urlString = "http://www.x86map.com/post-embed/ewspost";
StringBuffer s = new StringBuffer();
try
{
String line = null;
BufferedReader input = new BufferedReader(new FileReader("C:\\SupportXml.xml"));
while ((line = input.readLine()) != null)
{
s.append(line);
s.append(System.getProperty("line.separator"));
}
String xmlDataString = s.toString();
int length = xmlDataString.length();
System.out.println("length " + length);
URL url = new URL(urlString);
System.out.println(url.toString());
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setAllowUserInteraction(false);
connection.setUseCaches(false);
connection.setRequestProperty("Accept", "*/*");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", (String.valueOf(length)));
connection.setRequestProperty("Cache-Control", "no-cache");
connection.setRequestProperty("Accept-Language", "en-us");
connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8,q=0.66, *;q=0.66");
BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
BufferedReader reader = new BufferedReader(new StringReader(xmlDataString));
System.out.println("Proxy Used :" + connection.usingProxy());
int dataRead;
bos.write("XML_string=".getBytes());
while ((dataRead = reader.read()) != -1)
{
bos.write(dataRead);
}
bos.flush();
bos.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String res = null;
while ((res = br.readLine()) != null)
{
}
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
Please help me to resolve this issue.
Thanks and Regards,
map125
You may find it helps to include
requestStream.Flush();
before .Closeing it.
Stream.Flush
I do not see the code that actually gets the response. Is this want is missing?
using (var r = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.UTF8))
result = r.ReadToEnd();