Unable to post file in Python [Working in Java] - java

I'm quite new to Python and I've been trying to make a post request in Python by sending an xml file along with the request. In Java I could perfectly do it with the below piece of code
String url = "https://www.test.com"
URL object = new URL(url);
HttpURLConnection conn = (HttpURLConnection) object.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Content-Type", "application/xml");
conn.setRequestProperty("Accept", "application/xml");
conn.setRequestMethod("POST");
BufferedReader br = new BufferedReader((new FileReader("D:\\test.xml")));
String line1;
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
while ((line1 = br.readLine()) != null) {
wr.write(line1);
}
wr.flush();
wr.close();
int HttpResult = conn.getResponseCode();
To make it work in Python, I've tried different ways. None of them worked
headers = {"Content-type": "application/xml",
"Accept": "application/xml",
}
url = "https://www.test.com"
filePath = "D:\\test.xml"
file_data = [('file', (filePath, open(filePath), 'application/xml'))]
resp = requests.post(url = url, files=file_data, headers=headers)
print("resp=",resp.url)
print("resp=",resp)
And few other options as well
files = {'file':(filePath, open(filePath, 'rb'))}
files = {'file': (filePath, open(filePath, 'rb'), 'application/xml', {'Accept': 'application/xml'})}
Even I tried to send the file as data. But to no avail.
data = open("D:\\test.xml", 'rb').read()
resp = requests.post(url = url, data=data, headers=headers)
Please help me to understand where I'm Wrong. I've been breaking my head for hours.
FYI: I'm using Python 3.6.1

Looking at the official documentation of requests, I can find this example (adapted to your case):
url = "https://www.test.com"
filePath = "D:\\test.xml"
files = {'file': (filePath, open(filePath, 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
r = requests.post(url, files=files)
The original quickstart example is here:
https://requests.readthedocs.io/en/master/user/quickstart/#post-a-multipart-encoded-file

Related

Sending a JSON formatted string through HttpUrlConnection

I've done some research on using HttpUrlConnect and most examples I've seen uses either
a) a params string which looks like this:
paramString = "param1=someParam&param2=2ndparam&param3=3rdparam";
b) uses a put method to place the parameters:
JSONObject json = new JSONObject();
json.put("param1", "Parameter");
json.put("param2", "Parameter2");
json.put("param3", "Parameter3");
The format I want to send looks like this:
{
"grant_type":"password",
"username":"testuser#someid.com",
"password":"testPwd123$"
}
Is there a way for me to send a formatted JSON string instead of setting parameters or using a param string? The code I'm using to send my POST request looks like the following:
public static String PostRequest(String urlString, String token, String jsonString) throws IOException {
byte[] postData = jsonString.getBytes(StandardCharsets.UTF_8);
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty ("Authorization", "Bearer " + token);
conn.setUseCaches(false);
try( DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write(postData);
}
int responseCode = conn.getResponseCode();
System.out.println("POST response code: " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
StringBuffer response = new StringBuffer();
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
return response.toString();
}
I'm open to suggestions whether to use a different library, or if there are any code changes that I should make in order to take a JSON formatted string.

auth_key is required : Quickblox error

I am using Quickblox REST APIs. When i am trying to run from POSTMAN , it is giving me proper output. but , when i am using it through my java code. It is showing me below error :
auth_key is required
Here is my java code :
URL url = new URL("https://api.quickblox.com/session.json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
String current_date = dateFormat.format(cal.getTime());
Date newdt = dateFormat.parse(current_date);
long unixTime = newdt.getTime() / 1000;
String nonce = randomString(5);
String message ="application_id=XXXXX&auth_key=XXXXX&nonce=xxxxtimestamp=xxxx";
JSONObject arrayElement = new JSONObject();
arrayElement.put("application_id", "xxxxxx");
arrayElement.put("auth_key", "xxxxxxx");
arrayElement.put("nonce", nonce);
arrayElement.put("timestamp", unixTime);
arrayElement.put("signature", hmacDigest(message, secret, "HmacSHA1"));
conn.setRequestProperty("data", arrayElement.toJSONString());
conn.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
HashMap hmdata = new HashMap();
while ((inputLine = in.readLine()) != null) {
hmdata.put("data", inputLine);
}
in.close();
Can anybody help me to resolve this error?
If you send as json then add the following header:
conn.setRequestProperty("Content-Type", "application/json");
because the server does not understand in what format you send the request's payload

Java Post Data HttpsUrlConnection or HttpClient 4.5

I am trying to do what I thought was a simple task. I need to POST data to a PHP server. I have tried this solution but in Apache HttpClient 4.5 I can't find BasicNameValuePair in the package. Upon further research I thought I'd try StringEntity...nope not in 4.5 either (that I can find at least). So I tried to do it with HttpsURLConnection. The problem with that is I can't figure out how to add a name to my parameter and with a name, I don't know how to access in PHP with $_POST['name'].
My Current Code:
String json = gson.toJson(data);
URL url = new URL("https://www.domain.com/test.php");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(json.length()));
OutputStream os = conn.getOutputStream();
os.write(json.getBytes());
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
Try to use DataOutputStream and flush it afterward.
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeChars(json);
wr.flush();
wr.close();

Won't send all parameters to post http request

I am trying to send a http request with java. This is my code:
String AnnonseUrl = "http://webpage.no/insert_annonse.php?info="+info+"&tittel="+tittel+"&bedriftsNavn="+bedriftsNavn+"&kontaktEmail="+kontaktEmail+"&varighet="+varighet+"&frist="+frist+"&url="+url+"&sted="+sted+"&kontaktNavn="+kontaktNavn;
URL url = new URL(AnnonseUrl);
URLConnection uc = url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
uc.getInputStream()));
in.close();
Only the first three parameters are submitted..
If I copie the string "AnnonseUrl" and paste it in to my browser, then everything works fine.
When doing a post the parameters are send in the Http Body:
Try this:
URL u = new URL("http://www.stackoverflow.com");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.connect();
DataOutputStream wr = new DataOutputStream (
conn.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush();
wr.close();
Where urlParameters is something like:
String urlParameters =
"tittel="+URLEncoder.encode(tittel,"UTF-8")
+"&bedriftsNavn"+URLEncoder.encode(bedriftsNavn,"UTF-8");

Manually hitting a SOAP Service in Java, getting IO.FileNotFound exception

I need to access a .Net SOAP Service manually. All the importers have issues with its WSDL, so I'm just manually creating the XML message, using HttpURLConnection to connect, and then parsing the results. I've wrapped the Http/SOAP call into a function that is supposed to return the results as a string. Here's what I have:
//passed in values: urlAddress, soapAction, soapDocument
URL u = new URL(urlAddress);
URLConnection uc = u.openConnection();
HttpURLConnection connection = (HttpURLConnection) uc;
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("SOAPAction", soapAction);
connection.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
connection.setRequestProperty("Accept","[star]/[star]");
connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
OutputStream out = connection.getOutputStream();
Writer wout = new OutputStreamWriter(out);
//helper function that gets a string from a dom Document
String xmldata = XmlUtils.GetDocumentXml(soapDocument);
wout.write(xmldata);
wout.flush();
wout.close();
// Response
int responseCode = connection.getResponseCode();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String responseString = "";
String outputString = "";
//Write the SOAP message response to a String.
while ((responseString = rd.readLine()) != null) {
outputString = outputString + responseString;
}
return outputString;
My problem is on the line BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); I get a "java.io.FileNotFoundException" with the address that I'm using (i.e. urlAddress). If I paste that address into a browser, it pulls up the Soap Service webpage just fine (address is http://protectpaytest.propay.com/API/SPS.svc). From what I've read, the FileNotFoundException is if the HttpURLConnection returns a 400+ error message. I added the line getResponseCode() just to see what the exact code was, and it's 404. I added the User-Agent and Accept headers from some other pages saying they were needed, but I'm still getting 404.
Are there other headers I'm missing? What else do I need to do to get this call to work (since it works in a browser)?
-shnar

Categories