i have a problem when using webrequest to pass to php
so i need to pass a parameter to php look like this
this is in php
public function get_token()
{
$client = new \GuzzleHttp\Client;
$requestdata = [
[
"name"=>'grant_type',
"contents" => 'client_credentials'
],
[
"name"=>'client_id',
"contents" => 'testclient'
],
[
"name"=>'client_secret',
"contents" => 'abcdefghijklmnopqrstuvwxyz12341234567890'
]
];
$response = $client->request('POST','http://abc123.local/authorizations', [
'multipart' => $requestdata
]);
$data = $response->getBody()->getContents();
$data = json_decode($data, TRUE);
$token = $data['token_type'].' '.$data['access_token'];
return $token;
}
and this is my code in vb.net
Sub token()
Dim grand_type As String = "client_credentials"
Dim client_id As String = "testclient"
Dim client_secret As String = "abcdefghijklmnopqrstuvwxyz12341234567890"
Dim strHeaders As String
Dim urlAuth As String = "http://abc123.local/authorizations"
strHeaders = String.Format("grant_type={0}&client_id={1}&client_secret={2}",
grand_type, client_id, client_secret)
Dim JSONEncode As String
JSONEncode = JsonConvert.SerializeObject(strHeaders)
Dim byteData As Byte() = Encoding.UTF8.GetBytes(JSONEncode )
Dim httpReq As HttpWebRequest = TryCast(HttpWebRequest.Create(urlAuth), HttpWebRequest)
httpReq.Method = "POST"
httpReq.ContentType = "multipart/form-data"
httpReq.ContentLength = byteData.Length
'-=-=-=-=-=-=-=-= Sample Sending Data -=-=-=-=-=-=-=-
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
ServicePointManager.ServerCertificateValidationCallback =
New System.Net.Security.RemoteCertificateValidationCallback(AddressOf AcceptAllCertifications)
Dim reqStream As Stream = httpReq.GetRequestStream()
reqStream.Write(byteData, 0, byteData.Length)
Dim request As WebRequest = WebRequest.Create(urlAuth)
'-=-=-=-=-=-=-=-= Sample Receiving Data -=-=-=-=-=-=-=-=
Dim resStream As Stream = httpReq.GetResponse.GetResponseStream()
Dim objReader As New StreamReader(resStream, Encoding.UTF8)
Dim wr As WebResponse = httpReq.GetResponse()
Dim receiveStream As Stream = wr.GetResponseStream()
Dim reader As New StreamReader(receiveStream, Encoding.UTF8)
Dim content As String = reader.ReadToEnd()
End Sub
Private Function AcceptAllCertifications(sender As Object, certification As System.Security.Cryptography.X509Certificates.X509Certificate,
chain As System.Security.Cryptography.X509Certificates.X509Chain, sslPolicyErrors As System.Net.Security.SslPolicyErrors) As Boolean
Return True
End Function
i got an error for bad request, for this part:
"Dim resStream As Stream = httpReq.GetResponse.GetResponseStream()"
any idea? thanks
already found an answer, got it from
http://howtostartprogramming.com/vb-net/vb-net-tutorial-51-httpwebrequest-post-method/
thanks
I have a vb.net application where i am sending error string to a php page to process it.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim errorString As String = "test string"
Dim request As WebRequest = WebRequest.Create("http://10.0.0.1/test.php")
request.Method = "POST"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(errorString)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
MsgBox(responseFromServer)
End Sub
The responseFromServer is empty. Doesn't show the errorString.
My php page for testing looks like this:
<?php
if (isset($_POST['errorString']))
{
$a = $_POST['errorString'];
echo $a;
}
else
{
echo "ERROR: No data!";
}
?>
Does anyone know what I am missing? Any help would be greatly appreciated.
Thanks in advance!
In your request string you have to add key value parameters like this,
Dim errorString As String = "errorString=test string"
This is because in php code you are using errorString as POST parameter to receive data for that key value, so always send data with respect to the POST/GET key you are using in PHP code.
I am having trouble sending the post variable to received in the PHP document in my server. I tried it with the GET and it works fine. But what I notice is the POST VARIABLE doesn't receive the content I am sending. This is my code:
VB.NET WINFORM CODE
enter code here
Dim Username = TxtUser.Text
Dim PostData = "user_name=" & Username
Dim request As WebRequest = WebRequest.Create("http://website.com/test.php")
request.Method = "POST"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(PostData)
request.ContentType = "application/x-form-urlencoded"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
MsgBox(responseFromServer)
PHP CODE
<?php
//I tried this $user_name= 'SOMETHING'; and works fine.
$user_name= $_POST['user_name'];
?>
Changing the ContentType should do the trick.
request.ContentType = "application/x-www-form-urlencoded"
I am trying to send a document file from Lotus Script to a web server and save it there. Unfortunately the file transfer does not work. I have a Lotusscript agent to get the document and this part is working ( str_filecontent contains the correct xml file ), but the file transfer or saving is not working. Here is my Lotusscript agent:
Option Public
Option Declare
Sub Initialize
'Declare long
Dim lng_resolveTimeout, lng_connectTimeout, lng_sendTimeout, lng_receiveTimeout As Long
'Declare integer
Dim int_serverCredentials As Integer
'Declare variants
Dim var_submitObject As Variant
'Set values
int_serverCredentials = 0
lng_resolveTimeout = 120000 'miliseconds = 2 minutes
lng_connectTimeout = 1200000
lng_sendTimeout = 1200000
lng_receiveTimeout = 1200000
'Create HTTP object
Set var_submitObject = CreateObject("WinHTTP.WinHTTPRequest.5.1")
Call var_submitObject.SetTimeouts(lng_resolveTimeout, lng_connectTimeout, lng_sendTimeout, lng_receiveTimeout)
'Standards for this post
%REM
Content-Type: multipart/form-data; boundary={boundary}
{boundary}
Content-Disposition: form-data; name="data"; filename="{filename}"
Content-Type: text/plain
{contents}
{boundary}--
%END REM
Dim str_url As String
str_url = "http://.../upload.php"
Dim str_AUTH As String
Dim str_boundary As String
Dim str_filecontent As String
str_filecontent = get_data()
Dim submitHTTP
'Set post parameters
Call var_submitObject.open("POST", str_url, False)
Call var_submitObject.setRequestHeader("Accept", "application/xml")
Call var_submitObject.setRequestHeader("Authorization", "Basic " & str_auth)
Call var_submitObject.setRequestHeader("Content-Type", "multipart/form-data; boundary=b1")
str_boundary = |--b1| & Chr(13) & Chr(10) &_
|Content-Disposition: form-data; name="data"; filename="name.txt"| & Chr(13) & Chr(10) &_
|Content-Type: text/plain| & Chr(13) & Chr(10) &_
str_fileContent & |b1--|
'Send the HTTP request
Call var_submitObject.Send(str_boundary)
'Wait for the answer and set object as returned value for further validation
Call var_submitObject.WaitForResponse
Set submitHTTP = var_submitObject
'Clear memory
Set var_submitObject = Nothing
End Sub
%REM
Function get_data
Description: Comments for Function
%END REM
Function get_data() As String
Dim session As New NotesSession
Dim doc As NotesDocument
' Dim db As NotesDatabase
Dim exporter As NotesDXLExporter
' Set db = session.CurrentDatabase
Dim workspace As New NotesUIWorkspace
Dim uidoc As NotesUIDocument
Set uidoc = workspace.CurrentDocument
Set doc = uidoc.Document
' Set doc = SESSION.CU
Set exporter = session.CreateDXLExporter
get_data = exporter.Export(doc)
Print get_data
End Function
Here is my web server PHP to receive and save the file:
<?php
define("UPLOAD_DIR", "/temp/");
if (!empty($_FILES["data"])) {
$myFile = $_FILES["data"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
}
?>
Thanks for your time!
I am trying to access the post data sent from VB.net in PHP. But the POST data seems to be empty. I don't know much about vb.net.
vb.net code
Imports System.Net
Imports System.Text
Imports System.IO
Imports System.Net.NetworkInformation
Imports System.Net.Sockets
Imports Microsoft.Win32
Imports System.Security.Cryptography
Imports System.Net.Security
Public Class frmRegistration
Dim xx As Integer
Dim yy As Integer
Private Sub txtPhoneNo_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtPhoneNo.KeyPress
Select Case e.KeyChar
Case "0" To "9"
Case vbBack
Case Else
e.KeyChar = ""
End Select
End Sub
Private Function UrlSend(ByRef url As String)
Dim reader As StreamReader
Dim resUri As String
Dim req As HttpWebRequest = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
Try
Dim Res As HttpWebResponse = req.GetResponse()
Dim response As HttpWebResponse
response = req.GetResponse
resUri = response.ResponseUri.AbsoluteUri
reader = New StreamReader(response.GetResponseStream())
resUri = reader.ReadToEnd()
Return resUri
Catch ex As Exception
Return ex.Message
End Try
End Function
'Function Send(ByRef url As String, ByVal key As String) As String
' Dim TID = key
' Try
' Dim request As WebRequest = WebRequest.Create(url)
' request.Method = "POST"
' Dim byteArray As Byte() = Encoding.UTF8.GetBytes(TID)
' request.ContentType = "application/x-www-form-urlencoded"
' request.ContentLength = byteArray.Length
' Dim dataStream As Stream = request.GetRequestStream()
' dataStream.Write(byteArray, 0, byteArray.Length)
' dataStream.Close()
' Dim response As WebResponse = request.GetResponse()
' dataStream = response.GetResponseStream()
' Dim reader As New StreamReader(dataStream)
' Dim responseFromServer As String = reader.ReadToEnd()
' reader.Close()
' dataStream.Close()
' response.Close()
' Return responseFromServer
' Catch ex As Exception
' If Ping_Internet("www.google.com") = 1 Then
' MsgBox("Server not responding. Please try later.")
' End If
' Me.Close()
' End
' Return DBNull.Value.ToString
' End Try
'End Function
Public Function Ping_Internet(ByVal Activeurl As String) As Integer
Dim contact As String
Try
contact = My.Settings("TollFree").ToString
Dim strip = System.Net.Dns.GetHostEntry(Activeurl).AddressList(0).ToString
Dim ping As New System.Net.NetworkInformation.Ping
If ping.Send(strip).Status = IPStatus.Success Then
Return 1
Else
MsgBox("You are not connected to the Internet. If you are unable to get connected, contact us for help on our toll-free number(" & contact & ") at any time. ")
End
End If
Catch ex As Exception
MsgBox("You are not connected to the Internet. If you are unable to get connected, contact us for help on our toll-free number(" & contact & ") at any time. ")
End
End Try
Return 0
End Function
Function Domain_Check(ByVal emailid As String) As Boolean
If emailid.Contains("#") Then
Dim Domain As String() = emailid.Split("#")
Dim br As Boolean
Try
Dim ipHost As IPHostEntry = Dns.GetHostEntry(Domain(1))
br = True
Return br
Catch se As SocketException
br = False
Return br
End Try
Else
Return False
End If
End Function
Function IsValidEmailFormat(ByVal s As String) As Boolean
Try
Dim a As New System.Net.Mail.MailAddress(s)
Catch
Return False
End Try
If Domain_Check(s) = True Then
Return True
End If
Return True
End Function
Private Sub pnlOk_Click(sender As System.Object, e As System.EventArgs) Handles pnlOk.Click
If txtName.Text = "" Then
MsgBox("Please Enter Your Name!")
txtName.Focus()
Exit Sub
ElseIf txtPhoneNo.Text = "" Then
MsgBox("Please Enter Your Phone Number!")
txtPhoneNo.Focus()
Exit Sub
ElseIf IsValidEmailFormat(txtEmail.Text.ToString.Trim) = False Then
MsgBox("Please Enter a Valid Email Id!")
txtEmail.Focus()
Exit Sub
ElseIf txtKey.Text = "" Then
MsgBox("Please Enter Product Key Which Was Provided In Your Mail!")
txtKey.Focus()
Exit Sub
End If
Dim url = My.Settings("checkkey").ToString
Dim key = "rqtoken=" & txtEmail.Text.Trim & "|" & txtKey.Text.Trim
Dim resp = UrlSend(url & "?" & key).ToString.Trim
If resp = "OK" Then
Setregistry()
Else
MsgBox(resp)
End If
End Sub
Private Sub Setregistry()
Try
If WinVersion() Then
Registry.LocalMachine.CreateSubKey("SOFTWARE\Microsoft\Windows\Services")
End If
Dim Fullmsg As String = txtName.Text.Trim & "|" & txtPhoneNo.Text.Trim & "|" & txtEmail.Text.Trim & "|" & txtKey.Text.Trim
My.Computer.Registry.SetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Services", "xxxxxxx", AESEncrypt(Fullmsg), Microsoft.Win32.RegistryValueKind.String)
Application.Restart()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Function AESEncrypt(ByVal PlainText As String) As String
Dim InitialVector As String = "CanEncryption123"
If (String.IsNullOrEmpty(PlainText)) Then
Return ""
Exit Function
End If
Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector)
Dim PlainTextBytes As Byte() = Encoding.UTF8.GetBytes(PlainText)
Dim KeyBytes As Byte() = {Convert.ToByte(170), Convert.ToByte(89), Convert.ToByte(62), Convert.ToByte(253), Convert.ToByte(87), Convert.ToByte(232), Convert.ToByte(224), Convert.ToByte(53), Convert.ToByte(148), Convert.ToByte(2), Convert.ToByte(68), Convert.ToByte(185), Convert.ToByte(49), Convert.ToByte(60), Convert.ToByte(133), Convert.ToByte(82), Convert.ToByte(136), Convert.ToByte(27), Convert.ToByte(239), Convert.ToByte(160), Convert.ToByte(91), Convert.ToByte(67), Convert.ToByte(207), Convert.ToByte(233)}
Dim SymmetricKey As RijndaelManaged = New RijndaelManaged()
SymmetricKey.Mode = CipherMode.CBC
Dim CipherTextBytes As Byte() = Nothing
Using Encryptor As ICryptoTransform = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes)
Using MemStream As New MemoryStream()
Using CryptoStream As New CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write)
CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length)
CryptoStream.FlushFinalBlock()
CipherTextBytes = MemStream.ToArray()
MemStream.Close()
CryptoStream.Close()
End Using
End Using
End Using
SymmetricKey.Clear()
Return Convert.ToBase64String(CipherTextBytes)
End Function
Private Sub pnlCancel_Click(sender As System.Object, e As System.EventArgs) Handles pnlCancel.Click
txtName.Text = ""
txtPhoneNo.Text = ""
txtEmail.Text = ""
txtKey.Text = ""
txtName.Focus()
End Sub
Public Function WinVersion() As Boolean
Dim ver = Environment.OSVersion.Version.Major
If ver > 5 Then
Return True
Else
Return False
End If
End Function
Private Sub pnlOk_MouseEnter(sender As Object, e As System.EventArgs) Handles pnlOk.MouseEnter, pnlOk.MouseLeave
If pnlOk.Tag = 1 Then
pnlOk.BackgroundImage = My.Resources.ok_bttn_hover
pnlOk.Tag = 2
ElseIf pnlOk.Tag = 2 Then
pnlOk.BackgroundImage = My.Resources.ok_bttn
pnlOk.Tag = 1
End If
End Sub
Private Sub pnlCancel_MouseEnter(sender As Object, e As System.EventArgs) Handles pnlCancel.MouseEnter, pnlCancel.MouseLeave
If pnlCancel.Tag = 1 Then
pnlCancel.BackgroundImage = My.Resources.cancel_bttn_hover
pnlCancel.Tag = 2
ElseIf pnlCancel.Tag = 2 Then
pnlCancel.BackgroundImage = My.Resources.cancel_bttn
pnlCancel.Tag = 1
End If
End Sub
Private Sub pcbMin_Click(sender As System.Object, e As System.EventArgs) Handles pcbMin.Click
Me.WindowState = FormWindowState.Minimized
End Sub
Private Sub pcbCross_Click(sender As System.Object, e As System.EventArgs) Handles pcbCross.Click
End
End Sub
Private Sub pnlPan_MouseHover(sender As Object, e As System.EventArgs) Handles pnlPan.MouseHover
xx = Windows.Forms.Cursor.Position.X - Me.Left
yy = Windows.Forms.Cursor.Position.Y - Me.Top
End Sub
Private Sub pnlPan_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles pnlPan.MouseMove
If e.Button = Windows.Forms.MouseButtons.Left Then
Me.Left = Windows.Forms.Cursor.Position.X - xx
Me.Top = Windows.Forms.Cursor.Position.Y - yy
Else
xx = Windows.Forms.Cursor.Position.X - Me.Left
yy = Windows.Forms.Cursor.Position.Y - Me.Top
End If
End Sub
Private Sub Label3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label3.Click
End Sub
End Class
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Reg_Scan.My.MySettings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<system.diagnostics>
<sources>
<!-- This section defines the logging configuration for My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
<!-- Uncomment the below section to write to the Application Event Log -->
<!--<add name="EventLog"/>-->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
initializeData="FileLogWriter"/>
<!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
<!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
</sharedListeners>
</system.diagnostics>
<userSettings>
<xxx_xxxx.My.MySettings>
<setting name="TollFree" serializeAs="String">
<value />
</setting>
<setting name="checkkey" serializeAs="String">
<value>http://www.xxxx.com/xxxx.php</value>
</setting>
</xxx_xxxx.My.MySettings>
</userSettings>
Php code
<?php
if($_POST)
{
$email = $_POST["emailid"];
$key = $_POST["key"];
try {
$conn = new PDO('mysql:host=localhost;dbname=xxx_xxx_xx', 'xxxxx', 'xxxxxx');
$stmt = $conn->prepare("SELECT * FROM customer WHERE email=:email");
$stmt->bindValue(':email', $email);
$stmt->execute();
$rows = $stmt->fetch(PDO::FETCH_OBJ);
if ($rows > 0) {
if ( $rows->license_key == $key )
{
echo 'OK'
} else {
echo 'Invalid License Key
Please check your license key or Contact Support Admin
xxx#xxx.com';
}
} else {
echo 'Invalid Email ID
Please check your Email ID or Contact Support Admin
xxx#xxx.com';
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
?>
The php code is working fine as I tested it with an HTML form. Need help in finding why the vb.net form is not sending any post data.
Actually, your commented out 'Send' method will work better than the method you have in there now.
But you need to change the second line - I don't know if the parameter name "tid" is correct, but you can adjust that.
Function Send(ByRef url As String, ByVal key As String) As String
Dim TID = "tid=" & key;
Try
Dim request As WebRequest = WebRequest.Create(url)
request.Method = "POST"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(TID)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
Return responseFromServer
Catch ex As Exception
If Ping_Internet("www.google.com") = 1 Then
MsgBox("Server not responding. Please try later.")
End If
Me.Close()
End
Return DBNull.Value.ToString
End Try
End Function
Well I installed Fiddler and saw that the VB.NET code was generating GET get request as
GET/license_register.php?rqtoken=username#mail.com%7Cpassword
which has the value as
username#mail.com|password
modified my php code to read the GET parameters
$getstring = $_GET["rqtoken"];
list($email, $key) = explode("|", $getstring);