Skip to content

Instantly share code, notes, and snippets.

@marnitto
Created February 24, 2021 04:04
Show Gist options
  • Save marnitto/7992b248093669edd4c1075934cb86eb to your computer and use it in GitHub Desktop.
Save marnitto/7992b248093669edd4c1075934cb86eb to your computer and use it in GitHub Desktop.
Jython example script to send POST request which size is over 65536 byte
# -*- coding: utf-8 -*-
# HTTP POST request example to resolve post size bug in Jython.
#
# Jython from 2.7.1 can't use synchronous socket to send data more than
# 65536 bytes at once (sends first socket and blocks infinitely), because
# jython didn't catch if socket.sendall() sends successfully. This bug was
# reported at 2017 but until now(2021.2.) there is no official fix, so
# instead of waiting I made a simple script using Java's native
# `java.net.URLConnection` class.
#
# Tested on Jython 2.7.1 + Oracle JDK 1.8
#
# References:
# - https://bugs.jython.org/issue2618
# - https://bugs.jython.org/issue2508
from java.net import URL
from java.io import DataOutputStream
# Java native HTTPClient; jython can't send longer than 65536bytes to send
def http_request_reqonly(url, data):
con = URL(url).openConnection()
con.setRequestMethod('POST')
con.setRequestProperty('Content-Type', 'application/x-www-form-urlencoded')
con.setRequestProperty('Accept', 'text/plain')
con.setConnectTimeout(5*1000)
con.setReadTimeout(60*1000)
con.setInstanceFollowRedirects(False)
con.setDoOutput(True)
wr = DataOutputStream(con.getOutputStream())
wr.writeBytes(bytes(urllib.urlencode(data)))
wr.flush()
wr.close()
status_code = con.getResponseCode()
con.disconnect()
return status_code
# Usage example
http_request_reqonly('http://localhost:5000/push', {
'foo': 'bar'
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment