How to retrieve file contents to upload in API? Solved - java

I'm stuck in a problem of trying to upload something with a File parameter...
I had the idea of acquiring the string of the file, but I realized that I need to acquire the file's contents. How do you retrieve the file contents and upload it to the designated site?
EDIT: Managed to find problem
Here's the solution:
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("https://api.teknik.io/upload/post");
FileBody bin = new FileBody(new File("C:/Users/hp/Desktop/hid.txt"));
HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", bin).build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
System.out.println(EntityUtils.toString(resEntity));
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
It returns:
HTTP/1.1 200 OK
Response content length: 119
[{"results":
{"file":{"name":"rB8mlB.txt","url":"https://u.teknik.io/rB8mlB.txt","type":"inode/x-empty","size":0}}}]
I managed to make it work on a pdf file, but txt files are problematic
HTTP/1.1 200 OK
Response content length: 126
[{"results":{"file":{"name":"RfWjkg.pdf","url":"https://u.teknik.io/RfWjkg.pdf","type":"application/pdf","size":341852}}}]

use MultipartRequest jar file.
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import java.util.*;
import com.oreilly.servlet.*;
public class UploadServlet extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException , ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
MultipartRequest mpr=new MultipartRequest(req,getServletContext().getRealPath("file"),500*1024*1024);
out.println("<html><body><h3>File Uploaded<h3></html></body>");
}
}
call this servlet on upload button.

Related

Java Cannot resolve method 'getEntity' in 'HttpResponse'

So these are the imports that I use:
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.net.URIBuilder;
import java.net.URI;
And this is code that I made:
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
But I get this error:
Cannot resolve method 'getEntity' in 'HttpResponse'
I tried looking for solutions, but they were all for Android. I am using Java, and I use IntelliJ
This code comes from this sample:
// // This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org /httpcomponents-client-ga/)
public class JavaSample
{
public static void main(String[] args)
{
HttpClient httpclient = HttpClients.createDefault();
try
{
URIBuilder builder = new URIBuilder("https://gateway.apiportal.ns.nl/reisinformatie-api/api/v2/departures");
builder.setParameter("station", "{string}");
builder.setParameter("uicCode", "{string}");
builder.setParameter("dateTime", "{integer}");
builder.setParameter("lang", "nl");
builder.setParameter("maxJourneys", "{integer}");
URI uri = builder.build();
HttpGet request = new HttpGet(uri);
request.setHeader("Ocp-Apim-Subscription-Key", "{subscription key}");
// Request body
StringEntity reqEntity = new StringEntity("{body}");
request.setEntity(reqEntity);
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null)
{
System.out.println(EntityUtils.toString(entity));
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
What am I doing wrong?
This solved the problem:
ClassicHttpResponse response = (ClassicHttpResponse) httpclient.execute(request);
HttpEntity entity = response.getEntity();

How to modify a request body before forwarding it

I want to do the same functionality in the HttpPost, using servlets that is, instead of creating the request using HttpPost, I want to use another request coming from a servlet and change body before forwarding it to the URL "www.url.com/cgi-bin", how can I change the body content of a request ?
public void call() throws ClientProtocolException, IOException, InterruptedException {
String url = "www.url.com/cgi-bin"
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost(url);
String data = "body data";
InputStream stream = new ByteArrayInputStream(data.getBytes("UTF-8"));
InputStreamEntity reqEntity = new InputStreamEntity(stream, -1);
reqEntity.setChunked(true);
httppost.setEntity(reqEntity);
httppost.addHeader("charset", "utf-8");
httppost.setHeader("Content-Type", "text/xml");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
httpclient.getConnectionManager().shutdown();
}
I want it to be like...
#WebServlet("/myServlet/*")
public class MyHandler extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response) {
// add data to request here ...
// forward request to the URL ...
}
}
Unfortunately it is not possible, using servlet api's, for a servlet to generate a new post request with body content.

REST PUT with external file JSON to httpClient Java?

I need to translate this for example :
curl -X PUT -u ident:pass -H "Content-Type : application/json" --data-binary #G:\jonJob.json "http://localhost:8080/jobs/"
(this works).
in java with httpClient. I have try a lot of things but nothing work..
Someone could help me please ?
What I've tried :
public class PostFile {
#SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("ident", "pass");
provider.setCredentials(AuthScope.ANY, credentials);
HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
HttpPut httppost = new HttpPut("http://localhost:8080/jobs/");
File file = new File("G:/jsonJob.json");
HttpEntity httpEntity = MultipartEntityBuilder.create().addBinaryBody("file", file, ContentType.create("application/json"), file.getName()).build();
httppost.setEntity(httpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpClient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpClient.getConnectionManager().shutdown();
}
}
Result : "HTTP/1.1 415 Not supported type" (unsupported media type)
for your http req headers -H you have java runnable imple with interceptor:
public void run() {
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(YourConnectionMgr.getInstance())
.addInterceptorLast(new HttpRequestInterceptor() {
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
if (request.getRequestLine().getMethod() == "POST"){
request.addHeader("Content-Type", "application/json") ;
see examples here to figure out 'connectionManager'
for simple auth, add this
to map in memory and POST a file see answer here
Note, you will eventually want some kind of async http client for java , you can google for that. The apache examples like in the link provided are mostly blocking network calls AFAIK

how to read http get response (restful-ws) as java.io.file

File file = new File("C:\\testing.txt")
Can we achieve by any means somthing like:
File file = new File("https://stackoverflow.com/ws-server/lookup/1.0/1234")
The below webservice returns me the same file content as txt in string form.
https://stackoverflow.com/ws-server/lookup/1.0/1234
Can anyone please let me know if its doable.
You can write the response to a File.
Look at this answer for details.
After this you can just open the File as you are used to.
Is this a convenient implementation? NOTE: it uses Apache HttpComponents Client and Apache Commons IO
public class RunApp {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet("http://localhost/");
System.out.println("Executing request " + httpget.getRequestLine());
// Create a custom response handler
ResponseHandler<File> responseHandler = new ResponseHandler<File>() {
public File handleResponse( final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
File file = new File("Desired-filename");
IOUtils.copy(entity.getContent(), new FileOutputStream(file));
return file;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
};
File file = httpclient.execute(httpget, responseHandler);
System.out.println("----------------------------------------");
System.out.println(file.getAbsolutePath());
} finally {
httpclient.close();
}
}
}
An even shorter solution would be to use FileUtils.copyURLToFile(URL, File) from Apache Commons IO

Uploading file from android (java) to server using PHP

Hello Im trying to upload files from my android application to my server using PHP.
I have read this posts:
How to upload a file using Java HttpClient library working with PHP
http://www.veereshr.com/Java/Upload
How do I send a file in Android from a mobile device to server using http?
This is my JAVA code:
public void upload() throws Exception {
File file = new File("data/data/com.tigo/databases/exercise");
Log.i("file.getName()", file.getName());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://***.***.***.***/backDatabase.php");
InputStreamEntity reqEntity = new InputStreamEntity( new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
if((response.getStatusLine().toString()).equals("HTTP/1.1 200 OK")){
// Successfully Uploaded
Log.i("uploaded", response.getStatusLine().toString());
}
else{
// Did not upload. Add your logic here. Maybe you want to retry.
Log.i(" not uploaded", response.getStatusLine().toString());
}
httpclient.getConnectionManager().shutdown();
}
This is my PHP code:
<?php
$uploads_dir = '/tigo/databaseBackup';
if (is_uploaded_file($_FILES['exercise']['tmp_name']))
{
$info = "File ". $_FILES['exercise']['name'] ." uploaded successfully.\n";
$file = 'emailTest.log';
file_put_contents($file, $info, FILE_APPEND | LOCK_EX);
move_uploaded_file ($_FILES['exercise'] ['tmp_name'], $_FILES['exercise'] ['name']);
}
else
{
$info = "Possible file upload attack: ";
$file = 'emailTest.log';
file_put_contents($file, $info, FILE_APPEND | LOCK_EX);
$info = "filename '". $_FILES['exercise']['tmp_name'] . "'.";
file_put_contents($file, $info, FILE_APPEND | LOCK_EX);
print_r($_FILES);
}
?>
In my logcat i get HTTP/1.1 200 OK.
When i look at the server logs i get this error:
PHP Notice: Undefined index: exercise in /var/www/backDatabase.php on line 23
I also tried to use:
$_FILES['userfile']['name']
Instead of
$_FILES['exercise']['tmp_name']
And i got the same error in my server logs.
I think my problem is that I cant get reference to my uploaded file.
Thanks for helping.
try multipart entity
public void upload(String filepath) throws IOException
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("url");
File file = new File(filepath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
// check the response and do what is required
}
Try this:
JAVA code:
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
public class UploadFile {
public static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://***.***.***.***/backDatabase.php");
File file = new File("/data/data/com.tigo/databases/exercise");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
}
PHP code:
<?php
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $_FILES['userfile'] ['name']);
} else {
echo "Possible file upload attack: ";
echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
print_r($_FILES); }
?>
You may need to change the paths in order to fit your needs, but the above code works.
Upload Image on Web Server using Android / C# {Xamarin}
This is Just Small Piece of Code. it can send any image from Android to your Web
Server using Android
System.Net.WebClient Client = new System.Net.WebClient();
Client.Headers.Add("Content-Type", "binary/octet-stream");
byte[] result = Client.UploadFile("localhost/FolderName/upload.php", "POST", path);
string s = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);
Here is the PHP Code {upload.php}. Create a Folder name { Uploads } in
your Application.
<?php
$uploads_dir = 'uploads/'; //Directory to save the file that comes from client application.
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK)
{
$tmp_name = $_FILES["file"]["tmp_name"];
$name = $_FILES["file"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
?>

Categories