before I ever send data and images with success, but it was done with two different procedures
this is my code to send data
public class HTTPPostData extends AsyncTask {
#Override
protected String doInBackground(String... urls) {
String Result = "";
byte[] Bresult = null;
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL_TO_LOAD);
try {
List<NameValuePair> nameValuePairs = LPD;
post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
Bresult = EntityUtils.toByteArray(response.getEntity());
Result = new String(Bresult, "UTF-8");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
}
return Result;
}
protected void onPostExecute(String result) {
// dismiss the dialog after the file was downloaded
if (!result.toString().trim().equals("")) {
RunProcedure.StrParam = result;
RunProcedure.run();
}
}
}
and this my code to transfer pic
public boolean TransferFileToHttp(String address_to_handle, String file_name) {
boolean result = false;
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
// DataInputStream inputStream = null;
String pathToOurFile = file_name;
String urlServer = address_to_handle;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(new File(
pathToOurFile));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream
.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ pathToOurFile + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
result = true;
} catch (Exception ex) {
// Exception handling
result = false;
}
return result;
}
how to joining transfer file procedure to post data procedure and retrieve string as a result?
It is absolutely possible to do so. However, you will have to perform some additional steps.
You will first have to convert the image to a base 64 string. Refer to this document
http://developer.android.com/reference/android/util/Base64.html
Now the string can be sent as regular json data.
On the server end, you will need a mechanism to convert back the base64 string to image. It is a trivial task though.
There are some disadvantages of this method such as huge size of json request and additional overhead of encoding/decoding.
Related
I am uploading video from android app.i am able to add only video with this code,but i am giving request with video file,but its not working.i added code with this question,help me out from this.
public int uploadFile(final String sourceFileUri) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String action ="action=videoUpload&id="+pHelper.getuser_id()+"&project_id="+Constants.proj_id+"&site_id="+count_et;
Log.d("bf_encoding",action);
// encode
byte[] data = new byte[0];
try {
data = action.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String value = Base64.encodeToString(data, Base64.DEFAULT);
String twoHyphens = "--";
String boundary = "*****";
String mm = "gokgo8gg4ko4gco4okg4ws4o04k44w0go4k";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
return 0;
} else {
try {
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL("https://rahumanmusic.co.in/ar_site/api/video");
Log.d("WebService", "url=" + url);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
// conn.setRequestProperty("Headers","X-API-KEY=gokgo8gwskkog4ko4gco4okgo04k44w0go4k");
// conn.getHeaderFieldDate("X-API-KEY", Long.parseLong(mm));
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
Log.d("valuevalue",value);
conn.setRequestProperty("video_upload", filepathUrl1.getName());
conn.setRequestProperty("value", value);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"video_upload\";filename=\"" + filepathUrl1.getName() + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (result)
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
result += line;
}
}
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.d("ssk", "result" + result);
return serverResponseCode;
} // End else block
}
In above code,converted base 64 string as value not passing in request. i am stuck in this task,help me out guys
Use this
library for multipart requests, i-e image, video or any other data for POST request
Is anybody aware of an Android app that acts as a REST API client and allows attaching files? I'm looking to do the equivalent of this in Postman, but from an Android device:
I've tried "REST Client for Android" and "HTTP Client" available on Google Play, but these only seem to allow text in the body, not file attachments. Can anybody advise on options for this for Android currently ??
https://futurestud.io/blog/retrofit-2-how-to-upload-files-to-server
pls find above link for retrofit api mostly used restapi.
Use HttpURLConnection class to upload image on server.
String urlStr= "url link";
String response;
boolean isGetMethod = false;
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DataOutputStream dataOutputStream;
String lineEnd = "\r\n", twoHyphens = "--", boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
File file;
int maxBufferSize = 1024 * 1024;
FileInputStream fileInputStream;
try {
URL url = new URL(urlStr);
httpURLConnection = (HttpURLConnection) url.openConnection();
if (!isGetMethod) {
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
file = new File("image file path");
fileInputStream = new FileInputStream(file);
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"; filename=\"" + file.getName() + "\"" + lineEnd);
dataOutputStream.writeBytes("Content-Type: image/jpeg" + lineEnd);
dataOutputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dataOutputStream.flush();
dataOutputStream.close();
}
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuilder builder = new StringBuilder();
while ((inputLine = bufferedReader.readLine()) != null) {
builder.append(inputLine);
}
response = builder.toString();
bufferedReader.close();
} else
return response;
} catch (Exception e) {
e.printStackTrace();
}
httpURLConnection.disconnect();
return response;
}
#Override
protected void onPostExecute(String response) {
}
}
I need to upload a photo taken by the camera's cellphone to a REST API called IMAGGA. I found in the API's documentation the following Java code:
String apiKey = "",
apiSecret = "";
HttpResponse response = Unirest.post("https://api.imagga.com/v1/content")
.basicAuth(apiKey, apiSecret)
.field("image", new File("/path/to/image.jpg"))
.asJson();
JSONObject jsonResponse = response.getBody().getObject();
System.out.println(jsonResponse.toString());
This code gives me an identifier, so I can use it to get the json from a image tagging.
I can't get it done because I'm using HttpURLConnection and I have no idea how to do that.
The only thing that i'm having problems with is the uploading part:
.field("image", new File("/path/to/image.jpg"))
To post an image to Imagga, use the postImageToImagga method below.
To do:
Please insert your own Basic Authorization details in the code from the Imagga dashboard, see the following line in code: connection.setRequestProperty("Authorization", "<insert your own Authorization e.g. Basic YWNjX>");
public String postImageToImagga(String filepath) throws Exception {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****"+Long.toString(System.currentTimeMillis())+"*****";
String lineEnd = "\r\n";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String filefield = "image";
String[] q = filepath.split("/");
int idx = q.length - 1;
File file = new File(filepath);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL("https://api.imagga.com/v1/content");
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
connection.setRequestProperty("Authorization", "<insert your own Authorization e.g. Basic YWNjX>");
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] +"\"" + lineEnd);
outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while(bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
inputStream = connection.getInputStream();
int status = connection.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
inputStream.close();
connection.disconnect();
fileInputStream.close();
outputStream.flush();
outputStream.close();
return response.toString();
} else {
throw new Exception("Non ok response returned");
}
}
To call the above code on a non-UI thread, we can use AsyncTask:
public class PostImageToImaggaAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
try {
String response = postImageToImagga("/mnt/sdcard/Pictures/Stone.jpg");
Log.i("imagga", response);
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
To call the above PostImageToImaggaAsync code:
PostImageToImaggaAsync postImageToImaggaAsync = new PostImageToImaggaAsync();
postImageToImaggaAsync.execute();
I have been using HttpUrlConnection to post a video and some other parameter,
the code runs fine else offcourse it does not post the data,it is able to get the
response from the server and i cant seem to figure out the issue.
Any help is appreciated ,Thankyou.
class MyAsyncTask extends AsyncTask<String, Void, String> {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
ProgressDialog dialog;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
int serverResponseCode = 0;
String line = null;
String floatMessage = null;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(EventsActivity.this);
dialog.show();
dialog.setMessage("Uploading Event");
dialog.setCancelable(false);
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls) {
try {
FileInputStream fileInputStream = new FileInputStream(new File(videopath));
URL url = new URL("http://workintelligent.com/TagFrame/webservice/upload_video");
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs.
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
// Set HTTP method to POST.
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("video_file", videopath);
Log.e("getting user_id", userid);
connection.setRequestProperty("user_id",userid);
connection.setRequestProperty("access_type ", "public");
connection.setRequestProperty("title", "sdfdsf");
connection.setRequestProperty("description", "sdscfsdf");
connection.setRequestProperty("tags_keywords", "asdf");
connection.setRequestProperty("price", "0");
connection.setRequestProperty("is_paid", "0");
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"video_file\";filename=\"" + videopath + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
connection.setRequestMethod("GET");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
fileInputStream.close();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + '\n');
}
String jsonString = stringBuilder.toString();
Log.e("jsonString", jsonString);
JSONObject resJson = new JSONObject(jsonString);
String floatMessage = resJson.getString("upload");
Log.e("floatMessage", floatMessage);
outputStream.flush();
outputStream.close();
} catch (Exception ex) {
}
return floatMessage;
}
protected void onPostExecute(String result) {
dialog.cancel();
super.onPostExecute(result);
Toast.makeText(EventsActivity.this, floatMessage, Toast.LENGTH_LONG).show();
}
}
I am uploading a file to a server and depending on the processing on the file I get a different reply from the server. Everything is working, however getting the reply from the server is very slow. I checked in the debugger and the following line of code is taking 6 seconds to run.
inStream = new DataInputStream( connection.getInputStream() );
I have tested the same files and code over a web browser and its perfect, taking about 1 or 2 seconds to display the reply. Here is my full code, I think its ok, but maybe there is something here that is not done properly. Is there a better way of doing this? Or is a new DataInputStream always going to be so slow?
private String loadImageFromNetwork(String myfile) {
HttpURLConnection connection = null;
DataOutputStream outStream = null;
DataInputStream inStream = null;
String make = "";
String model = "";
String disp = "";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String urlString = "http://xxxxxxxxxxxxxx/upload.php";
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + myfile)));
try {
FileInputStream fileInputStream = new FileInputStream(new File(myfile));
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs
connection.setDoInput(true);
// Allow Outputs
connection.setDoOutput(true);
// Don't use a cached copy.
connection.setUseCaches(false);
// Use a post method.
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outStream = new DataOutputStream(connection.getOutputStream());
outStream.writeBytes(twoHyphens + boundary + lineEnd);
outStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + myfile +"\"" + lineEnd);
outStream.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
outStream.writeBytes(lineEnd);
outStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
fileInputStream.close();
outStream.flush();
outStream.close();
}
catch (MalformedURLException ex) {
ex.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream( connection.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
disp = disp + str;
}
inStream.close();
}
catch (IOException ioex){
ioex.printStackTrace();
}
return disp;
}
You should move the code to read the response from the server to a new thread. Ex:
private class ReadResponse implements Runnable {
public void run() {
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream( connection.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
disp = disp + str;
}
inStream.close();
}
catch (IOException ioex){
ioex.printStackTrace();
}
//return disp;
//here you need to show your display on UI thread
}
}
}
and start the reading thread before uploading the file.