Is it possible to embed a file attachment in a JSON Object. I have a HTML Form, which has several text field inputs and a file attachment. I want to send a JSON Object wrapping all these form data (including the file attachment) to the server.
Are there any particular libraries in Java available to do that? Can you give possible solution for this.
Thanks
If you want to send the actual data of the file, you'd probably want to encode it as a base64 string and send that in your JSON - see fiddle for example of encoding it in javascript:
http://jsfiddle.net/eliseosoto/JHQnk/
Then you could do the opposite on your server-side using whatever language and/or libraries are appropriate.
Use MultipartEntity, someone else posted a similar question: How to send file in JSON on android?
You could also consider saving the files on the server and sending a path/url to the file location where the other server can access them.
public String SendToServer(String aUrl,File Filename)
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(filename);
try
{
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", new FileBody(Filename));
entity.addPart("video-title", new StringBody("Video"));
entity.addPart("video-type", new StringBody("1"));
httpPost.setEntity(entity);
HttpContext context = new BasicHttpContext();
// Bind custom cookie store to the local context
context.setAttribute(ClientContext.COOKIE_STORE, Globals.sessionCookie);
HttpResponse response = httpClient.execute(httpPost, context);
HttpEntity resEntity = response.getEntity();
String Response = "";
if (response != null)
{
Response = EntityUtils.toString(resEntity);
}
return Response;
}
catch (IOException e)
{
e.printStackTrace();
}
return "Exception";
}
Related
I'm new to android development and I'm working on an app that is supposed to send a local image file to a web service and get the response back.
I was able to send a URL of an image from general online sources through my code, and it worked.
But the requirement is to pass an image from the gallery via the API.
The Code I have set up is giving me an invalid URL error when I get the information for the image selected as below. How do I get around this to pass the image from the gallery?
The API allows for multipart/form-data too. I'm not sure how to extract the image data for it using the gallery data.
I have commented the line of code in the JSON object accumulate which does not work.
'''
//setting uploaded image to view
Uri selectedImage = data.getData();
//get url
String URILOCATION = selectedImage.getPath();
imageView.setImageURI(data.getData());
HttpClient httpclient = HttpClients.createDefault();
try
{
URIBuilder builder = new URIBuilder("https://eastus.api.cognitive.microsoft.com/customvision/v3.0/Prediction/aaead50a-95cd-403c-a3c2-9b774399e43b/classify/iterations/Iteration6/url");
URI uri = builder.build();
HttpPost request = new HttpPost(uri);
request.setHeader("Content-Type", "application/json");
request.setHeader("Prediction-key", predictionApiKey);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("url","https://i.ibb.co/XCnhQ2m/IMG20210503153531.jpg");
//jsonObject.accumulate("url",URILOCATION);
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// Request body
StringEntity reqEntity = new StringEntity(json);
request.setEntity(reqEntity);
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null)
{
System.out.println(EntityUtils.toString(entity));
}
'''
I am uploading a File from GWT to a different domain
File Uploads well , But the response i sent from the server always reaches as "null" at the client side
response.setContentType("text/html");
response.setHeader("Access-Control-Allow-Origin", "*");
response.getWriter().print("TEST");
response is NULL only when i upload the file on a different domain ... (on same domain all is OK)
I also see this in GWT documentation
Tip:
The result html can be null as a result of submitting a form to a different domain.
http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/ui/FormPanel.SubmitCompleteEvent.html
Is there any way I can receive back a response at my client side when i am uploading file to a different domain
There are 2 possible answer:
Use JSONP Builder
JsonpRequestBuilder requestBuilder = new JsonpRequestBuilder();
requestBuilder.requestObject(url, new AsyncCallback<FbUser>() {
#Override
public void onFailure(Throwable ex) {
throw SOMETHING_EXCEPTION(ex);
}
#Override
public void onSuccess(ResponseModel resp) {
if (resp.isError()) {
// on response error on something
log.error(resp.getError().getMessage())
log.error(resp.getError().getCode())
}
log.info(resp.getAnyData())
}
Not to use GWT to upload, rather use other client like apache HttpClient
public uploadFile() {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
FileBody bin = new FileBody(new File(UPLOADED_FILE));
long size = bin.getContentLength();
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("PART", bin);
String content = "-";
try {
httpPost.setEntity(reqEntity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity ent = response.getEntity();
InputStream st = ent.getContent();
StringWriter writer = new StringWriter();
IOUtils.copy(st, writer);
content = writer.toString();
} catch (IOException e) {
return "false";
}
return content;
}
Hope it helps
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'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 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.