Hello im trying to send a multipart post request and using jython with commons httpclient 4.3.1.
http_client = DefaultHttpClient()
http_post = HttpPost(url)
bin = FileBody(File(file_name), ContentType.APPLICATION_XML)
me = MultipartEntity()
me.addPart('datei', bin)
http_post.setEntity(me)
print "Executing Post Request:", http_post.getRequestLine()
http_response = http_client.execute(http_post)
result_entity = http_response.getEntity()
return EntityUtils.toString(result_entity)
In my opinion the return value should a str with the content, but it is:
"type 'org.apache.http.conn.BasicManagedEntity'"
Where is my mistake?
I do not know the exact answer to your question. And today I have been trying to make a multipart post work from my jython script for a skiuli project I am working on.
Here is how I was able to do it.
First get ez_setup.py from: http://peak.telecommunity.com/dist/ez_setup.py
Then run jython ez_setup.py from the cmd prompt
Second get poster from: http://atlee.ca/software/poster/dist/0.8.1/
Unzip the file
Then run jython setup.py install
Last you can follow this sample code or see more on the atlee site:
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2
register_openers()
upload_url = "http://your.website.com/upload-multipart.php"
#this will upload a file and a json object
#in php the file is in $_FILES and the json is in $_POST
params = {'file': open("test.txt", "rb"), 'jsonData': '[{"foo":"bar", "foo1":"bar1"}]'}
datagen, headers = multipart_encode(params)
request = urllib2.Request(upload_url, datagen, headers)
result = urllib2.urlopen(request)
print result.read()
I hope this helps someone out there. This example will also work for post multipart in python.
Related
I am trying to migrate one of api test to karate framework. However I am unable to write the corrent step defined in karate documentation. Maybe I am missing some basic syntax..but could anyone have any idea how we write following steps in karate feature
requestPostDoc.header("x-api-key","FG6dcYHN9N7PYKfWCUlGo5QGTwZhv2Re1MrDSOTV");//New chnages
requestPostDoc.contentType("multipart/form-data").multiPart("part2-file",file).formParam("part1-json",objDocumentWrite.toJSONString());
requestPostDoc.queryParam("loadProperties",true); //New changes
responseForNewCaseDocFile=requestPostDoc.post("https://vrh0oox3hl.execute-api.eu-central-1.amazonaws.com/default/");//New changes
filterableRequestSpecification = (FilterableRequestSpecification) requestPostDoc;
filterableRequestSpecification.removeQueryParam("loadProperties");
I have written following feature file in karate:
Given url 'https://vrh0oox3hl.execute-api.eu-central-1.amazonaws.com/default/'
And header x-api-key = 'FG6dcYHN9N7PYKfWCUlGo5QGTwZhv2Re1MrDSOTV'
And header Authorization = 'Bearer ' + jwt
And param loadProperties = true
And multipart file info = { read: 'classpath:testData/documentWrite.json', filename: 'documentWrite.json' }
And multipart file Uploading = { read: 'classpath:testData/TextFile.txt', filename: 'TextFile.txt' }
When method post
Then print response
Then status 200
When I execute this test i am getting 400 response code
status code was: 400, expected: 200, response time in milliseconds: 252, url: https://vrh0oox3hl.execute-api.eu-central-1.amazonaws.com/default/?loadProperties=true, response:
Based on the cURL command in the comments, this is my best guess. The rest is up to your research. Read the docs and tweak the Content-Type and other sub-headers if needed. You need to figure this out depending on what your server wants: https://github.com/karatelabs/karate#multipart-file
* multipart file part1-json = { read: 'documentWrite.json' }
* multipart file part2-file = { read: 'TextFile.txt' }
For anyone coming across this question in the future and if you are stuck, get a friend if needed and go through this exercise together: https://github.com/karatelabs/karate/issues/1645#issuecomment-862502881
This stuff can be hard and needs time. There are no short cuts.
I am creating an api which allows downloading a zip file, so for this I am looking for correct media type for sending this zip file as response in swagger "2.0" specification.
My current api spec looks like this
/config:
get:
produces:
- application/zip
responses:
200: # OK
description: All config files
schema:
type: string
format: binary
I have compiled this spec with "go-swagger" and implemented the backend for this, but when try to call this API I get this error
http: panic serving 127.0.0.1:20366: applicationZip producer has not yet been implemented
In the documentation of swagger I don't see this media type
Official swagger media types
So then what should be the correct media type if we want to provide an API to download a zip file.
Thanks in advance
You need to implement this.
The error occurs because of the following generated code:
func NewSampleAPI(spec *loads.Document) *SampleAPI {
return &SampleAPI{
...
ApplicationZipProducer: runtime.ProducerFunc(func(w io.Writer, data interface{}) error {
return errors.NotImplemented("applicationZip producer has not yet been implemented")
}),
So after calling NewSampleAPI, you should set ApplicationZipProducer:
api := operations.NewSampleAPI(swaggerSpec)
api.ApplicationZipProducer = func(w io.Writer, data interface{}) error {
...
}
You should use "application/octet-stream" for implementing api that downloads file as an attachment , and since its Producer is already implemented by default so you won't face this issue.
As mentioned in other answer, using "application/octet-stream" partially solves the issue, but the browser does not know the file format. I think that his can be improved adding the correct headers to the response, that will tell the browser that the file has a zip extension. At least, I can download a file as ZIP and Firefox recognizes it.
#Operation(summary = "Downloads a ZIP file)
#GetMapping(value = "/zip", produces="application/octet-stream")
public byte[] start(HttpServletResponse response) {
final ContentDisposition contentDisposition = ContentDisposition.builder("attachment")
.filename("MyFile.zip").build();
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());
return getZipDataAsByteArray();
}
I'm trying to upload a pdf file with form-data to a server. The upload works but the file gets corrupted for some reason (I can't open the uploaded version). Here's my code:
post_url = 'https://myposturl'
headers = {
'Content-Type':'multipart/form-data; charset=UTF-8; boundary=MyBoundary'
}
with open('./myfile.pdf', 'rb') as f:
body = f'--MyBoundary\r\nContent-Disposition: form-data; name="file"; filename="myfile.pdf"\r\nContent-Type: application/pdf\r\n\r\n{f.read()}\r\n--MyBoundary--\r\n'
res = s.post(post_url, headers = headers, data = body)
I thought it was coming from the \r\n, I tried a replace('\n', '\r\n') on the f.read() output but it didn't work.
Also, when using https://httpbin.org to check the POST request, I get \\\\r\\\\n for each new line in the pdf binary data. I'm wondering if this is normal, maybe that could help.
Thank you in advance for your suggestions.
With requests it can be done a bit easier.
import requests
post_url = 'https://myposturl'
files = {'file': open('./myfile.pdf', 'rb')}
r = requests.post(post_url, files=files)
More docs.
The reason you get corrupted file is probably because you're setting headers and body manually. requests usually sets theses things implicitly, so you should not break this concept and follow official guides.
I am trying to make a simplified version of test report where I am generating a single HTML file report containing only assertion and error response message when there is any (attempting to not publish all the logs and steps).
I understand that we have hooks in karate. However I have looked for karate objects in the github but unable to found any objects where I can extract the response from (to be passed to the js function called on hook)
What I am doing right now is this:
Config:
//karate-config.js
karate.configure('afterScenario', karate.call('classpath:hooks.js'));
Hook:
//hooks.js
//Looking on how to extract the response and log it here
function(){
var info = karate.tags;
karate.log('Tags', info);
}
Am I missing anything on the karate objects? Or this should be achieved in another way?
Thanks a lot!
Try this:
var response = karate.get('response');
EDIT better example:
Background:
* configure afterScenario = function(){ karate.log('***', karate.get("response.headers['X-Karate']")) }
Scenario:
Given url 'http://httpbin.org'
And path 'headers'
And header X-Karate = 'test'
When method get
# this will fail
Then status 400
I have tried with both karate.get('response') and response directly, and both work. If you use karate.call() pass the response as a parameter.
I just started learning how to use API and I found some really usefull websites and apps like Postman and import.io yet I'm having problems finishing it without help.
I started my little project by getting a working api from import.io (It reads a website and can give you a working API that finds the info in the website)
My REST API looks like this:
https://extraction.import.io/query/runtime/7629f27e-ceee-4ce2-9a1c-cede623d2fc0?_apikey=[apiKey]&url=http%3A%2F%2Fimdb.com
To test and make sure it's working I used postman app and then found a neat feature - code generation.
The app generated this code:
import http.client
conn = http.client.HTTPSConnection("extraction.import.io")
headers = {
'cache-control': "no-cache",
'postman-token': "2087cc79-77b5-0cb9-aa06-adc642978287"
}
conn.request("GET", "/query/runtime/1ac40e3e-f3eb-4290-88c0-e2651b8194a5?_apikey=[apiKey]&url=http%253A%252F%252Fwww.leagueofgraph.com", headers=headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
however the result is:
{
"message" : "Your extraction request has failed.",
"code" : 1003
}
What am I doing wrong?
The code that has been generated has double escaped the "http://"
it should be http%3A%2F%2F not http%253A%252F%252F
Try this corrected code:
import http.client
conn = http.client.HTTPSConnection("extraction.import.io")
headers = {
'cache-control': "no-cache",
'postman-token': "2087cc79-77b5-0cb9-aa06-adc642978287"
}
conn.request("GET", "/query/runtime/1ac40e3e-f3eb-4290-88c0-e2651b8194a5?_apikey=[apiKey]&url=http%3A%2F%2Fwww.leagueofgraph.com", headers=headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))