0

I'm trying to POST some data using VB.NET to PHP. The PHP script, shown below, is just two lines for experimentation.

$arr = array('code' => '110', 'description' => $_POST['updateDate']);
echo json_encode($arr);

In VB I have tried to POST using WebClient, HttpClient and HttpWebRequest. Only WebClient worked as expected. The other two returned "Undefined index: updateDate" meaning that POST was not correct. Below is the VB code.

Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Web.Script.Serialization
Imports System.Collections.Generic
Imports System.Collections.Specialized
Imports System.Net.Http
Imports System.Threading.Tasks
Imports System.Windows.Forms

Public Class frmMain
    Dim hclient As HttpClient = New HttpClient

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim request As HttpWebRequest
        Dim response As HttpWebResponse
        Dim byteArray() As Byte
        Dim dataStream As Stream
        Dim reader As StreamReader

        Dim sresponse As String
        Dim serializer As New JavaScriptSerializer()
        Dim responseBytes As Byte()

        Dim client As New WebClient
        Dim postData As New NameValueCollection
        postData.Add("updateDate", "17-02-2020")
        responseBytes = client.UploadValues("http://localhost/srvMoveTimesARGUS/srvMoveTimesARGUS.php", postData)
        sresponse = Encoding.UTF8.GetString(responseBytes)


        Dim updateData As New List(Of field) From {
            New field With {.fieldValue = "17-02-2020", .fieldName = "updateDate"}
        }
        Dim arrayJson As String
        arrayJson = serializer.Serialize(updateData)

        '---------------------------------------------------------
        'With hclient
        '   .BaseAddress = New Uri("http://localhost/srvMoveTimesARGUS/srvMoveTimesARGUS.php")
        '   .DefaultRequestHeaders.Accept.Clear()
        '   .DefaultRequestHeaders.Accept.Add(New Headers.MediaTypeWithQualityHeaderValue("application/json"))
        'End With

        'PostAsync(arrayJson)
        '---------------------------------------------------------

        '---------------------------------------------------------
        'byteArray = Encoding.UTF8.GetBytes(arrayJson)
        'request = HttpWebRequest.Create("http://localhost/srvMoveTimesARGUS/srvMoveTimesARGUS.php")

        'request.Method = "POST"
        'request.ContentType = "application/json"
        ''request.Accept = "application/json"
        'request.ContentLength = byteArray.Length
        ''request.Expect = "application/json"

        'dataStream = request.GetRequestStream
        'dataStream.Write(byteArray, 0, byteArray.Length)
        'dataStream.Close()

        'response = request.GetResponse
        'dataStream = response.GetResponseStream()
        'reader = New StreamReader(dataStream)
        'sresponse = reader.ReadToEnd

        'reader.Close()
        'dataStream.Close()
        'response.Close()
        '---------------------------------------------------------
    End Sub

    Private Async Function PostAsync(ByVal jsonString As String) As Task

        Dim content As New Net.Http.StringContent(jsonString, System.Text.Encoding.UTF8, "application/json")
        Dim response As Net.Http.HttpResponseMessage = Await hclient.PostAsync("", content)

        Dim result As String = Await response.Content.ReadAsStringAsync()

        MessageBox.Show(result)
    End Function
End Class

Public Class field
  Public Property fieldName As String
  Public Property fieldValue As String
End Class

Variable arrayJson that holds the serialised string takes the value

"[{""fieldName"":""updateDate"",""fieldValue"":""17-02-2020""}]"

2 Answers 2

1

https://www.php.net/manual/en/reserved.variables.post.php

An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

If you want to access the raw request body it will be in the stream php://input and can be accessed simply with:

$json_string = file_get_contents('php://input');
Sign up to request clarification or add additional context in comments.

2 Comments

That did the trick. But using HttpClient and HttpWebRequest I'm setting the headers to application/json so why the data that I'm sending are not shown into _POST?
Because JSON is not one of the two Content-Types that PHP cares about.
0

Here's what I did and worked for me , for those who still looking for good answer:

Imports System.Collections.Generic
Imports System.Threading.Tasks
Imports Newtonsoft.Json


Sub PostData()
Dim dbdictionary As New Dictionary(Of String, Object)

        dbdictionary.Add("ptdata", t1ds)
        dbdictionary.Add("data", t2ds)
        textstring = JsonConvert.SerializeObject(dbdictionary)

        Dim httpWebRequest = CType(WebRequest.Create("https://yourserver.com/post.php"), HttpWebRequest)
        httpWebRequest.ContentType = "text/json"
        httpWebRequest.Method = "POST"

        Using streamWriter = New StreamWriter(httpWebRequest.GetRequestStream())

            streamWriter.Write(textstring)
        End Using

        Dim httpResponse = CType(httpWebRequest.GetResponse(), HttpWebResponse)

        Using streamReader = New StreamReader(httpResponse.GetResponseStream())
            Dim responseText = streamReader.ReadToEnd()
            Typethis(responseText)
        End Using

End Sub

That Posts to PHP file containing this :

header("Content-Type: application/json; charset=UTF-8");
$data   = file_get_contents('php://input');
//print_r($data);
echo file_get_contents('php://input');
$Storagebackup = "backups/".strtotime("now");
$cmnt =$data  ;
$myfile = fopen($Storagebackup.".txt", "w") or die("Unable to open file!");//w means write - a means apppend n file 
$txt = $cmnt;
fwrite($myfile, $txt);
fclose($myfile);


echo "Thats all<br>";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.