I wanted to send XML file as attachment over URL from Java class
Code with which i am trying is as below
File request_XML_file = new File("src/request.xml");
URL url = new URL("https://************?p_xml_file="+request_XML_file);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("enctype","multipart/form-data");
But value passed for p_xml_file is src/request.xml
You can also consider the new features of Java 7
Path path = Paths.get("/tmp/foo/bar.txt"); Files.createDirectories(path.getParent()); try { Files.createFile(path); } catch (FileAlreadyExistsException e) { System.err.println("already exists: " + e.getMessage()); } } }
Kindly use this link
http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/PostXML.java?view=markup
DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost("http://localhost:8080/TESTINGrestful/rest/polls/comment"); StringEntity input = new StringEntity("<Comment>...</Comment>"); input.setContentType("text/xml"); postRequest.setEntity(input); HttpResponse response = httpClient.execute(postRequest);
After 2 days search got some use full stuff and its worked for me.. No need to import any additional Jar file..
If we wanted to send an file as attachment over RESTFul Web service URL MultipartUtility is correct why to do it..
Here we go..!! A ready made code --> http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically
Related
I've installed BIRT Web-Viewer on my server and am able to build the report with this URL:
http://hostname:port/birt/run?__report=test.rptdesign
Now I need to programmatically call this URL from my Java Code and retrieve the result as stream or file.
Is there any API for the Web-Viewer?
If not, could I just call the URL like this and extract the PDF?:
HttpClient httpClient = HttpClients.createDefault();
HttpGet postRequest = new HttpPost("http://hostname:port/birt/run");
List<NameValuePair> formData = new ArrayList<>();
formData.add(new BasicNameValuePair("__report", "test.rptdesign"));
HttpEntity entity = new UrlEncodedFormEntity(formData);
HttpResponse response = httpClient.execute(postRequest);
I found out, if I use the __format parameter with the value pdf, the response to the request is the PDF content, which is exactly what I wanted.
The standard response is a HTML, which will be returned with a second request. I'm pretty sure that response has to be retrieved with sessions.
Edit:
As requested I will post my request code. I modified it a bit, because I used some custom classes to hold configuration and the report.
public InputStream getReport() throws Exception {
StringBuilder urlBuilder = new StringBuilder()
.append("http://example.com:9080/contextRoot/run")
.append("?__report=ReportDesign.rptdesign&__format=pdf");
if (reportParameters != null) {
for (Map.Entry<String, String> parameter : reportParameters.entrySet()) {
String key = StringEscapeUtils.escapeHtml(parameter.getKey());
String value = StringEscapeUtils.escapeHtml(parameter.getValue());
urlBuilder.append('&')
.append(key);
.append('=');
.append(value);
}
}
URL requestUrl = new URL(burlBuilder.toString());
HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.connect();
return connection.getInputStream();
}
I also had another method write the used data as XML to the file system before I called requestUrl.openConnection(), but I think this is only necessary if you use very dynamic data like I did.
I would like to order sent to the POST request with a parameter in the form of a JPG file.
I use HttpClient in version 4.4.1
Part of the Java code looks like this:
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
File file = new File("path_to_jpg");
HttpPost post = new HttpPost("http://localhost:1337/uploadJPG");
FileBody fileBody = new FileBody(file);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = httpclient.execute(post);
System.out.println(response.getEntity().getContent());
} finally {
httpclient.close();
}
next at "http://localhost:1337/uploadJPG" want to let nodeJS have a server that will process the JPG file
the idea of server code nodeJS:
var http = require('http'),
fs = require('fs'),
server = http.createServer( function(req, res) {
if (req.method == 'POST') {
//process file JPG
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('processed JPG');
}
});
port = 1337;
host = '127.0.0.1';
server.listen(1337, '127.0.0.1');
console.log('Listening at http://' + '127.0.0.1' + ':' + 1337);
and now my question is, How can I create such a service in NodeJS, which will have the file in jpg?
Not sure if you are using Express or not but if you are you can use a middleware like Multer which makes it very simple to handle MultiPart data and files.
I'm using the following code to send a http request to github.
String url = "https://api.github.com/repositories";
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(url);
// StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
// request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
System.out.println(json);
} catch (IOException ex) {
}
I got output: {"message":"Not Found","documentation_url":"https://developer.github.com/v3"}
If use directly put "https://api.github.com/repositories" in browser, a lot of useful information will be shown. My question is how can I get the information I see when using browser by using Java.
You should use HttpGet instead of HttpPost. Just like your browser sends a GET request.
I'm working in a E-Commerce website, with JSF 2.
In order to communicate with the company that makes all the operation with the banks, I need to send this XML to them (it's just a sample provided from them):
<?xml version="1.0" encoding="ISO-8859-1"?>
<requisicao-transacao versao="1.2.0" id="6560a94c-663b-4aec-9a45-e45f278e00b4" xmlns="http://ecommerce.cbmp.com.br">
<dados-ec>
<numero>1001734898</numero>
<chave>e84827130b9837473681c2787007da5914d6359947015a5cdb2b8843db0fa832</chave>
</dados-ec>
<dados-pedido>
<numero>1603662828</numero>
<valor>100</valor>
<moeda>986</moeda>
<data-hora>2010-07-14T15:50:11</data-hora>
<idioma>PT</idioma>
</dados-pedido>
<forma-pagamento>
<bandeira>visa</bandeira>
<produto>A</produto>
<parcelas>1</parcelas>
</forma-pagamento>
<url-retorno>https://www.dummyurl.du/dummypage.do?id=trhjgnerifvnidjfnvmd</url-retorno>
<autorizar>1</autorizar>
<capturar>true</capturar>
</requisicao-transacao>
So after reading a lot about how to send and XML and receive it, I create this method:
public String rent(){
//String folderAndFile = createTransaction();
//creating the HTTP Post
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://qasecommerce.cielo.com.br/servicos/ecommwsec.do");
try {
//Reading the file as an entity
FileEntity entity = new FileEntity(new File("/home/valter.silva/sample.xml"));
entity.setContentType("text/xml");
post.setEntity(entity);
HttpResponse response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
System.out.println(EntityUtils.toString(httpEntity));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
But the output is always :
INFO: <?xml version="1.0" encoding="ISO-8859-1"?> <erro xmlns="http://ecommerce.cbmp.com.br"> <codigo>001</codigo> <mensagem>Requisição inválida</mensagem> </erro>
Which means that my .xml that I'm sending is invalid. That for some reason, the XML is wrong.. but what ?
Is alright the way that I'm sending the file ? What can I do about it ?
update
I was trying another approach but still the output is always the same, ..., is something wrong with my code ?
//approach v1
public String rent(){
//String folderAndFile = createTransaction();
try {
File file = new File("/home/valter.silva/test.xml");
HttpPost post = new HttpPost("https://qasecommerce.cielo.com.br/servicos/ecommwsec.do");
post.setEntity(new InputStreamEntity(new FileInputStream(file),file.length()));
post.setHeader("Content-type", "text/xml; charset=ISO-8859-1");
//creating the HTTP Post
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
System.out.println(EntityUtils.toString(httpEntity));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//approach v2
public String rent(){
//String folderAndFile = createTransaction();
try {
File file = new File("/home/valter.silva/test.xml");
HttpPost post = new HttpPost("https://qasecommerce.cielo.com.br/servicos/ecommwsec.do");
//creating the HTTP Post
DefaultHttpClient client = new DefaultHttpClient();
String fileInString = fileToString("/home/valter.silva/test.xml");
InputStream inputStream=new ByteArrayInputStream(fileInString.getBytes());//init your own inputstream
InputStreamEntity inputStreamEntity=new InputStreamEntity(inputStream,fileInString.length());
post.setEntity(inputStreamEntity);
HttpResponse response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
System.out.println(EntityUtils.toString(httpEntity));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Can you check that the url where you trying to post can handle your xml correctly ?
I have tried to upload the xml you provided using just simple http post to the specified url and got
<?xml version="1.0" encoding="ISO-8859-1"?> <erro xmlns="http://ecommerce.cbmp.com.br"> <codigo>001</codigo> <mensagem>Requisição inválida</mensagem> </erro>
I prefer you first try to upload the xml from outside and then try with your code .
For example i used RESTClient of Mozilla addon .
I need to create Multi-part POST request containing fields:
update[image_title] = String
update[image] = image-data itself.
As you can see both are in associative array called "update".
How could I do it with HTTPClient 4.1, because I found only examples for 3.x line of this library.
Thank you in advance.
Probably too late but might help someone. I had the exact same issue.
Assuming that you have a file object which has necessary information about the image
HttpPost post = new HttpPost(YOUR_URL);
MultipartEntity entity = new MultipartEntity();
ByteArrayBody body = new ByteArrayBody(file.getData(), file.getName());
String imageTitle = new StringBody(file.getName());
entity.addPart("imageTitle", imageTitle);
entity.addPart("image", body);
post.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = null;
try {
response = client.execute(post);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Please note that MultiPartEntity is part of HttpMime module. So you need to put that jar in the lib directory or include as a (maven/gradle) dependency.
Yeah I've found it a real pain to find HTTP Client 4 examples, etc as well, since the almighty google almost always still points to HTTP 3.
At any rate, the last sample on this page - http://hc.apache.org/httpcomponents-client-ga/examples.html should be what you want.