Getting a 400 Bad Request error while trying to send JSON data to a PHP page via socket

Currently, I am in the process of developing a program that can gather temperature and humidity data from a Pysense device and then store this information in a database on my laptop. To accomplish this, I have set up a socket to send Json data via POST to a php page, where the data is decoded and entered into the database. However, I am encountering an issue where I receive a '400 bad request' response when attempting to send the data to the php page. It seems like the problem might be related to the formatting of the Json data, but despite searching online, I have not been able to find a solution that resolves this error for me. Below is the code snippet I am currently working with:

In this code, 'hum' and 'temp' represent the readings obtained from the device.

data = '{ "DeviceName": 1, "Humidity": %.2f, "Temperature": %.2f }'%(hum,temp)

header = ("""
POST /insert.php HTTP/1.1
Host: 192.168.4.2
Content-Type: application/json\r\n
""")

contentLengthStr = 'Content-Length : %s\r\n\r\n'%str(len(data))
request = header + contentLengthStr + data
print(request)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
s.send(request.encode())
response = s.recv(4096)
print(response)

I anticipated that the php page would decode the data, but instead, I received the following response displayed in the console:

HTTP/1.1 400 Bad Request\r\nDate: Tue, 29 Jan 2019 16:12:06 GMT\r\nServer: Apache/2.4.33 (Win32) OpenSSL/1.1.0h PHP/7.2.6\r\nVary: accept-language,accept-charset\r\nAccept-Ranges: bytes\r\nConnection: close\r\nContent-Type: text/html; charset=utf-8\r\nContent-Language: en\r\nExpires: Tue, 29 Jan 2019 16:12:06 GMT\r\n\r\n\r\n\r\n\r\nBad request!\r\n\r\n*/-->\r\n\r\n\r\n\r\nBad request!'

If you have any suggestions or solutions to offer, they would be greatly appreciated!

Answer №1

header = ("""
POST /insert.php HTTP/1.1
Host: 192.168.4.2
Content-Type: application/json\r\n
""")

When you use triple-quoted strings, they preserve all the information within them, including newlines. This can cause issues when concatenating with other strings, as shown in the request below:


POST /insert.php HTTP/1.1
Host: 192.168.4.2
Content-Type: application/json

Content-Length : 59

{ "DeviceName": 1, ... }

The extra blank line between Content-Type and Content-Length may cause problems. The leading blank line could also be problematic, although this is uncertain.

To avoid such errors, it's recommended to utilize a library like requests.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the concept of accessing multidimensional arrays in PHP using keys

This is the result retrieved from the server: Array ( [id] => 123 [status] => pending [recipient] => Array ( [account_id] => 5000 [gateway_id] => 51111 ) [amount] => Array ( [value] => 2 [currency] => RUB ) [description] => orde ...

Is there a way to determine if a button was clicked using twig?

I need assistance with implementing a button in my twig file within a table that will remove an element from an array. Ideally, I would like to remove the element based on its index. From the research I have conducted, it seems that data manipulation shou ...

What is preventing me from importing selenium?

Why am I unable to import selenium? Here is how my code appears in Visual Studio Code: https://i.stack.imgur.com/Goqde.png This issue only started after I upgraded to Windows 11, which resulted in the deletion of the C-drive. Does anyone have a solution ...

Sending the "accurate" data from the specific cell in a UITableViewController to a ViewController

I'm encountering the same issue here. I am struggling to pass the precise data from one TableViewController to another ViewController. Even though I have all the necessary data from JSON, when I select a row, it displays the data from the last row ins ...

Exploring the process of transforming a JSON array into separate JSON objects using Node.js

I am struggling with converting a JSON array to multiple JSON objects in Node.js. I've attempted using loops but have been unsuccessful. I'm seeking assistance to send the data as separate objects, not an array. router.get('/frontpage-mobil ...

What causes an Undefined array key error when using AJAX POST?

I am having trouble passing a text string to a PHP Variable using AJAX. Every time the POST request is sent, I see this error message: Warning: Undefined array key "mydata" Although the alert displays the correct value, the PHP page shows the ...

JSON is not conforming to the standard nesting level

After simplifying, the JSON implementation is as follows: Data(Entity)->"data"->another Entity I originally thought I could decrypt the Data object first, extract a type from it, and then use that type to decrypt the necessary type from the String "d ...

Dynamic classes cannot be utilized with concurrent.futures.ProcessPoolExecutor

Within the code snippet below, I am dynamically generating an object of a class using the `_py` attribute and the `generate_object` method. The code performs flawlessly without any issues when not utilizing concurrency. However, upon implementing concurre ...

Developing XML files with the CodeIgniter framework

I have implemented the following code in Codeigniter to generate XML: public function get_cuisine() { $this->load->dbutil(); $sql = "select * from cuisine"; $query = $this->db->query($sql); $config = array ( 'root& ...

Errors encountered while PHP processes XML file (RSS feed)

I am utilizing a PHP class that is based on this answer to parse five different RSS feeds. While four of the feeds are working perfectly fine, I am encountering errors with one specific feed. I am unsure if it is due to mal-formed XML or some other issue. ...

Tips for filtering out various values from a JSON String within a stored procedure in MS SQL

Looking for assistance with manipulating a JSON string. Here is the initial JSON: { "Country": { "Layer4": [ { "ItemName": "Cabinet MT", "ItemId": "cc3b0435-9ff5-4fd8-9f49-e ...

Adding up the elements of a numpy array

I am currently working on developing a polynomial calculator that allows me to input the largest coefficient. However, I am facing an issue with the xizes variable, which is producing multiple arrays representing the function image. As a result, the functi ...

Plugin for jQuery Validation: Verify if input is NOT an email address

I am currently updating a small Zend e-commerce website and we have been experiencing issues with robot inputs filling in email addresses in every field. To prevent this, I am looking to implement form validation that checks if the field does not contain a ...

Unable to make changes to the data

Journey Route::resource('/videofile', 'VideoController'); VideoController public function update(Request $req, $id){ $video = Video::findOrFail($id); if($req->hasFile('UserVideo')){ $vid = $req->file(& ...

What are some effective techniques for leveraging ElasticSearch's term queries in order to refine results by searching for a specific value within an array

I'm trying to make a POST request to an API in order to receive only the hits with the role "editor". The initial response, without any filters, appears as follows: _source: { configuration: { roles : [ {role : "lead"}, {role ...

Capturing information from a form containing various elements for storage

After following the instructions provided in https://symfony.com/doc/current/form/embedded.html, I encountered an issue when trying to submit a form containing three entities - Patient, PatientSample, and PatientOrder. The error message stating that patien ...

Why isn't my PHP code adding information to my MySQL database?

https://i.stack.imgur.com/a1eNG.jpgThe purpose of this script is to input data into a mysql database and generate JSON code for use in an Android application. However, during testing, the following result was obtained: Json Result after Testing On PostMan ...

What is the best way to combine lists within a `defaultdict` based on their keys while still maintaining the individual lists within each key?

I am looking to combine the lists within a defaultdict using keys as classes and list-values from two separate data sources. The goal is to merge the lists based on unique keys while keeping the values separate. Input: defaultdict(<class 'list&ap ...

Issue with Variable Inside While Loop

Currently, I am in the process of sending out a newsletter using the code shown below. The code involves a $to variable that contains email addresses stored in my database. To maintain privacy, I have implemented a while loop to send individual emails to e ...

Navigating through various div elements in Javascript and sending parameters to a script

Context In my project, I am using PHP to generate a series of voting sections. Each section follows the same format except for a unique number assigned to it, which increases with each iteration of the PHP loop. To keep track of the unique numbers, I uti ...