how to print http request to console
In Swift 5:
URLSession.shared.dataTask(with: request) { data, response, error in
print(String(data: data, encoding: .utf8)!)
}
If you are trying to see the whole HTTP request:
print("\(request.httpMethod!) \(request.url!)")
print(request.allHTTPHeaderFields!)
print(String(data: request.httpBody ?? Data(), encoding: .utf8)!)
You can add this last bit into an extension:
fileprivate extension URLRequest {
func debug() {
print("\(self.httpMethod!) \(self.url!)")
print("Headers:")
print(self.allHTTPHeaderFields!)
print("Body:")
print(String(data: self.httpBody ?? Data(), encoding: .utf8)!)
}
}
How to print the request body in console?
use a variable then print your request when you receive the response like this:
<html>
<body>
<script>
// POST request using fetch()
var user="hello";
let request = {
empUUID : user,
body: "bar",
userId: 1 ,
id: id
};
fetch("url",
{
// Adding method type
method: "POST",
// Adding body or contents to send
body: JSON.stringify(request),
// Adding headers to the request
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
// Converting to JSON
.then(response => response.json())
// Displaying results to console
.then(json => console.log("request:", request, ", response:", json));
}
</script>
</body>
</html>
Python function to print a dot to console while HTTP call executes
Every function call from the requests
module is blocking, so your program waits until the function returns a value. The simplest solution is to use the built-in threading
library which was already suggested. Using this module allows you to use code "parallelism"*. In your example you need one thread for the request which will be blocked until the request finished and the other for printing.
If you want to learn more about more advanced solutions see this answer https://stackoverflow.com/a/14246030/17726897
Here's how you can achieve your desired functionality using the threading
module
def print_function(stop_event):
while not stop_event.is_set():
print(".")
sleep(10)
should_stop = threading.Event()
thread = threading.Thread(target=print_function, args=[should_stop])
thread.start() # start the printing before the request
rsp = requests.Post(url, data=file) # start the requests which blocks the main thread but not the printing thread
should_stop.set() # request finished, signal the printing thread to stop
thread.join() # wait for the thread to stop
# handle response
* parallelism is in quotes because of something like the Global Interpreter Lock (GIL). Code statements from different threads aren't executed at the same time.
Python requests - print entire http request (raw)?
Since v1.2.3 Requests added the PreparedRequest object. As per the documentation "it contains the exact bytes that will be sent to the server".
One can use this to pretty print a request, like so:
import requests
req = requests.Request('POST','http://stackoverflow.com',headers={'X-Custom':'Test'},data='a=1&b=2')
prepared = req.prepare()
def pretty_print_POST(req):
"""
At this point it is completely built and ready
to be fired; it is "prepared".
However pay attention at the formatting used in
this function because it is programmed to be pretty
printed and may differ from the actual request.
"""
print('{}\n{}\r\n{}\r\n\r\n{}'.format(
'-----------START-----------',
req.method + ' ' + req.url,
'\r\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items()),
req.body,
))
pretty_print_POST(prepared)
which produces:
-----------START-----------
POST http://stackoverflow.com/
Content-Length: 7
X-Custom: Test
a=1&b=2
Then you can send the actual request with this:
s = requests.Session()
s.send(prepared)
These links are to the latest documentation available, so they might change in content:
Advanced - Prepared requests and API - Lower level classes
How do I print the content of httprequest request?
You can print the request type using:
request.getMethod();
You can print all the headers as mentioned here:
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
System.out.println("Header Name - " + headerName + ", Value - " + request.getHeader(headerName));
}
To print all the request params, use this:
Enumeration<String> params = request.getParameterNames();
while(params.hasMoreElements()){
String paramName = params.nextElement();
System.out.println("Parameter Name - "+paramName+", Value - "+request.getParameter(paramName));
}
request
is the instance of HttpServletRequest
You can beautify the outputs as you desire.
Flutter print any http request automatically - abstract HTTP class
well here is my last approach for this.
for every one is seeking for making it with abstraction or let's say wrapping;
first what I did is kind if wrapping for the HTTP class and used my class everywhere instead of the original Http Class.
so the code would go like this
class MHttpClient {
final http.Client client;
final SharedPreferences sharedPreferences;
MHttpClient(this.client, this.sharedPreferences);
Future<http.Response> get(
{String path = "", Map<String, String> extraHeders}) async {
printWrapped('get Path: $path');
final response = await client.get(
Uri.parse(getBaseURL() + Version + path),
headers: getHeaders(extraHeaders: extraHeders),
);
printWrapped("get response : \n" + utf8.decode(response.bodyBytes));
return response;
}
Future<http.Response> post(
{String body = "",
String path = "",
Map<String, String> extraHeders}) async {
printWrapped('sended body: \n');
printWrapped(' ${json.decode(body)}');
final response = await client.post(
Uri.parse(getBaseURL() + Version + path),
body: body,
headers: getHeaders(extraHeaders: extraHeders),
);
printWrapped("post response : \n" + utf8.decode(response.bodyBytes));
return response;
}
Future<http.Response> put({String body = "", String path = ""}) async {
printWrapped('put body: \n ${json.decode(body)}');
final response = await client.put(
Uri.parse(getBaseURL() + Version + path),
body: body,
headers: getHeaders(),
);
printWrapped(utf8.decode(response.bodyBytes));
return response;
}
Future<http.Response> putImage({File image, String path = ""}) async {
printWrapped('Image Path: $path');
final response = await http.put(
Uri.parse(path),
headers: getImageHeaders(),
body: image.readAsBytesSync(),
);
return response;
}
String getBaseURL() {
if (Foundation.kDebugMode)
return BaseURLSTAGING;
else
return BaseURL;
}
String getApiKey() {
if (Foundation.kDebugMode)
return ApiKeyStaging;
else
return ApiKey;
}
String getToken() {
String cashedToken = sharedPreferences.getString(CACHED_TOKEN);
if (cashedToken == null) cashedToken = "";
return cashedToken;
}
Map<String, String> getHeaders({Map extraHeaders}) {
Map<String, String> headers = {
'Content-Type': 'application/json; charset=UTF-8',
'x-api-key': getApiKey(),
HttpHeaders.authorizationHeader: 'Bearer ' + getToken(),
};
if (extraHeaders == null || extraHeaders.isEmpty)
return headers;
else {
headers.addAll(extraHeaders);
return headers;
}
}
Map<String, String> getImageHeaders() {
return <String, String>{'Content-Type': 'image/png'};
}
void printWrapped(String text) {
final pattern = RegExp('.{400}'); // 800 is the size of each chunk
pattern.allMatches(text).forEach((match) => developer.log(match.group(0)));
}
}
and then I used MHttpClient
else where
final MHttpClient client;
final response = await client.get(path: path);
and in this case I don't have to warry about anything else ,
and when you need to change one thing you will change it in one place only, and every thing will stay the same and work as you want without braking changes you have to do for all you requested.
How to print all information from an HTTP request to the screen, in PHP
Lastly:
print_r($_REQUEST);
That covers most incoming items: PHP.net Manual: $_REQUEST
how to print the data from post request on console
Use request.query when you have querystring params.
For form/post data use req.body.
In your case, use request.body.key
.
Related Topics
How to Declare Swift Generic for Enums of Particular Type
Strange String.Unicodescalars and Characterset Behaviour
Swift System Version Checking on Ubuntu
Does Swift Allow Code Blocks Without Conditions/Loops to Reduce Local Variable Scope
Bridging Header for Flurry.H Not Working with Pod
Where Do I Register a Valuetransformer in Swift
Swiftycam Capture Session Is Not Running
Uidatepicker Show Only Sunday's Date Only
Sizing a UIpickerview Inside a UIalertview
Detecting Swipes on All Four Directions on Watchkit Using The Storyboard
How to Get Reliable Timing for My Audio App
How Is Commoncrypto Used in Swift3
How to Create a Pulse Effect on an Skspritenode
Crash Casting Wknsurlrequest As? Other Type