Get reply from remote server using C# and PHP - c#

I'm trying to get data from a remote server using C#. I tried using a simple script to see if "it works", but I'm not getting a response. The same script works on a local server, so I'd like to know how I can do it.
This is my C# code:
IEnumerator Sayhi()
{
WWWForm sendInfo = new WWWForm();
sendInfo.AddField("function", function);
WWW www = new WWW(bl_LoginDataBase.Instance.GetUrl(bl_LoginDataBase.URLType.CallFunction), sendInfo);
yield return www;
Debug.Log(www.text);
}
And the PHP code:
<?php
echo "Hi";
I expected the Debug.Log(www.text); to print Hi, which it does if I use a local machine (http://192.168.0.whatever), but the remote server (http://whatever.example.com) doesn't return anything. I tried making the php fail so it returns an error, make a database and return some values from there, but nothing. I'd like to point out it does work on a local server, and works as intended.
What am I doing wrong?
Edit: By the way, if I access http://www.whatever.example.com/Function.php via browser, it shows the echo result.

C# has built in classes and methods to help you perform such tasks.You can use the WebClient class to connect to web servers (using GET or POST) and even send form values to it easily. See below:
string url ="http://www.whatever.example.com/Function.php";
var reqparam = new System.Collections.Specialized.NameValueCollection();
reqparam.Add("name", "John Doe");
try
{
using (System.Net.WebClient client = new System.Net.WebClient())
{
byte[] responsebytes = client.UploadValues(url, "POST", parameters);
string output = System.Text.Encoding.UTF8.GetString(responsebytes);
}
}
catch (Exception x)
{
//an error occured
}
The variable output will contain the response you want "Hi".

Related

UnityWebRequest not sending POST data

When Unity sends the POST request it doesn't pass the POST data, so the server returns an error (it gets the server response). I've seen that several people had a similar issue and it got fixed by adding www.chunkedTransfer = false;, however, that doesn't work for me.
I've also seen that some people use WWWForm instead of IMultipartFormSection, but I haven't tried it because it is deprecated.
I'm using PHP, but I've also tried it with Perl and it didn't work either. When I manually send a POST request everything works normally, so it seems the issue is in Unity. I'm new to Unity, so any help would be appreciated. I'm using the current latest version, 2018.2.18f1 Personal.
My code is pretty much the same as the official Unity documentation for sending POST request, but apparently it doesn't work. Here is my code:
C#:
public void Click() {
StartCoroutine(PostRequest("http://127.0.0.1/test.php", "help"));
}
IEnumerator PostRequest(string url, string data) {
List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
formData.Add(new MultipartFormDataSection("data=" + data));
UnityWebRequest www = UnityWebRequest.Post(url, formData);
www.chunkedTransfer = false;
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError) {
Debug.Log(www.error);
} else {
Debug.Log(www.downloadHandler.text);
}
}
PHP:
<?php echo "Server received: " . $_POST["data"]; ?>
Christoph Lütjen pointed out that according to this it should be new MultipartFormDataSection("data", data), despite the official documentation example using new MultipartFormDataSection("field1=foo&field2=bar").
Changing it to new MultipartFormDataSection("data", data) fixed the issue.

How can I successfully post JSON via C# to a Python Flask route that authenticates via the JSON content?

I've written a rudimentary API in a Flask project to allow POSTing data via JSON strings. The JSON requires two properties: username and apikey, which are validated through the following decorator:
def apikey_required(f):
#wraps(f)
def decorated_function(*args, **kwargs):
if not request.json:
abort(404)
json_data = request.json
if not 'username' in json_data or not 'apikey' in json_data:
abort(404)
user = User.query.filter(User.username == json_data['username']).first()
if not user or user.status != "superuser":
abort(404)
if not user.apikey or user.apikey != json_data['apikey']:
return jsonify({'status': 'error', 'message': 'unrecognized API key'})
return f(*args, **kwargs)
return decorated_function
I've written routes utilizing this decorator and they work beautifully in Python applications: Here's the basic structure of an API route:
#mod.route('/invadd', methods=['GET', 'POST'])
#apikey_required
def invadd():
json = request.json
#lots of application-specific logic that passes unit tests
My Flask unit tests work fine:
good_post_response = self.app.post(
'api/invadd', data=json.dumps(test_json),
content_type='application/json') # assertions which verify the reponse pass
Python applications I've written work fine:
response = urllib2.urlopen(req, json.dumps(post_json)) #req is an api route URL
response_json = json.loads(response.read())
But in my C# app, I get a SocketException: No connection could be made because the target machine actively refused it. when I try to post JSON to these same routes. Here's a relevant code snippet:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create();
request.ContentType = "application/json";
request.Method = "POST";
request.ContentLength = postJSON.Length;
using (StreamWriter sw = new StreamWriter(request.GetRequestStream())) <--- FAILURE POINT
{
sw.Write(postJSON.ToString());
sw.Flush();
sw.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
string result = sr.ReadToEnd();
AddFeedback(result);
}
I've also tried using the WebClient class:
WebClient wc = new WebClient();
AddFeedback(String.Format("Processing order {0}", order.OrderID));
string postJSON = BuildJSON(order);
string url = String.Format("{0}api/invadd", gslBase); //I verified that the URL is correctly constructed
string response = wc.UploadString(url, "POST", postJSON);
AddFeedback(response);
It's clear to me that the failure happens when the app tries to initiate the connection to the route, as it never gets to the point where it's actually trying to post the JSON data. But I'm not sure how to get around this. Do I need to change my Flask route?
That kind of exception indicates that there was a error at the socket level - that's before you reach JSON, or even HTTP.
Make sure you're connecting to the right machine and the right port.
It's not clear where you're inputting that data on your C# code - you probably should be using WebRequest.Create("yoururl") .
You can also try to connect using a browser, and see if it works.
If all those details are right, you can use wireshark to check what, exactly, is causing the connection to fail

Send XML to RESTful web service from Unity

I'm using WWW to interact with a RESTful web service. I have a problem sending XML files to the server through POST requests, though. This is my code:
if(Syste.IO.File.Exists(filePath)){
byte [] raw = File.ReadAllBytes(filePath);
WWWForm form = new WWWForm();
form.AddBinaryData("fileUpload", raw, "", "text/xml");
WWW www = new WWW(host + auth + "/behaviors", form);
StartCoroutine(myCoroutine(www));
}
IEnumerator myCoroutine(WWW www){
yield return www;
if (www.error == null)
{
Debug.Log("Text: " + www.text);
proceedToNextRequest = true;
} else {
Debug.Log("Error: "+ www.error);
Application.Quit();
}
}
The answer from the server is, though, "Unsupported Media Type", and I've no idea what's wrong. I generally use POSTMAN on Google Chrome to send these requests, and it works fine. Any tips?
I have found a solution for this: instead of using the WWW class(which, anyway, according to the documentation I'm pretty sure it can be used for this pupose), I'm using WebRequest. How this can be achieved is very well explained in the previous link and in this question: HTTP post XML data in C#

C# file uploading with a string using on PHP server

I am uploading a file with C# code on php server. But facing some issues.
First I was using a WebClient Object to upload file by calling UploadFile() method, and uploading string to by calling UploadString() method by following code:
String StoreID = "First Store";
WebClient Client = new WebClient();
String s = Client.UploadString("http://localhost/upload.php", "POST", StoreID);
Client.Headers.Add("Content-Type","binary/octet-stream");
byte[] result = Client.UploadFile("http://localhost/upload.php", "POST", "C:\\aaaa.jpg");
s = s + System.Text.Encoding.UTF8.GetString(result,0,result.Length);
Issue is that I am requesting two times so string and file is not being send at same time. I am receiving either String or File. But I need both at same time. I don't want to use UploadData() becuase it will use byte codes and I have know I idea how to extract it in php.
Let that string is folder name, i have to send string and file, so that file could save at specified folder at php server.
I studied there may be a solution with WebRequest and WebResponse object. But dont know how to send request using WebResponse by C# and get it at PHP.
Any Suggestions!!!!
Try this :
WebClient web = new WebClient();
try{
web.UploadFile("http://" + ip + "/test.php", StoreID);
}
catch(Exception e)
{
MessageBox.Show("Upload failed");
}
Now you can access the file from the PHP file.
<?php
//check whether the folder the exists
if(!(file_exists('C:/Users/dhanu-sdu/Desktop/test')))
{
//create the folder
mkdir('C:/Users/ComputerName/Desktop/test');
//give permission to the folder
chmod('C:/Users/ComputerName/Desktop/test', 0777);
}
//check whether the file exists
if (file_exists('C:/Users/ComputerName/Desktop/test/'. $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
//move the file into the new folder
move_uploaded_file($_FILES["file"]["tmp_name"],'C:/Users/ComputerName/Desktop/test/'. $_FILES["file"]["name"]);
}
?>
Also, you can download data from a PHP server and display it in a C# web browser by using the following codes :
WebClient web = new WebClient();
try{
byte[] response = web.DownloadData("http://" + ip +"/test.php");
webBrowser1.DocumentText = System.Text.ASCIIEncoding.ASCII.GetString(response);
}
catch(Exception e)
{
MessageBox.Show("Download failed");
}
You can create a webservice with php that accepts a file. Then publish that webservice, and add it to you c# references, then just call teh method from within your c# code that accepts the file, and vualá!
How to create SOAP with php link

Android application to send a simple form to a web service and get an sms in return

I'm trying to write an android application with a simple form. The user will send a string to a server and will get an SMS back with the same string + "thank you!".
I know Java but I'm more fluent in C#. I did manage to send the string to the web-service.
On Android Client:
public void sendFeedback(View button) {
final EditText nameField = (EditText) findViewById(R.id.EditTextName);
String name = nameField.getText().toString();
postData(name);
}
public void postData(String name) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:53811/WinnerSite/WebService.asmx?op=WriteToDB");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("json", name));
// nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
System.out.println(response.getFirstHeader(getPackageName()));
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
Web-Service is pretty slim:
[WebMethod]
public string WriteToDB(string json)
{
return "Hello World "+ json;
}
I ran the web-service with Visual-Studio built in server service.
The code behind the application got the string properly, but the code never recieved the string. Does someone has an idea what could be the problem?
the next phase, I cannot find the SMS email gate to SMS from my web-service SMS to one of the following Israeli operators:
Orange (a.k.a Partner)
Cellcom
Can someone help me find that gate?
try to use
JSONObject json = new JSONObject();
json.but("name",name)
and in the server send a message by using
json_encode("name than you ");
that may help you

Categories

Resources