I have this code which is able to upload a JPEG file to the server but the file is not recognized as JPEG. I think my problem is about encoding the JPEG file correctly. My solution is essentially the same as this one. I have tried other variants in appending the JPEG bytes using FileInputStream and using DataOutputStream instead of OutputStreamWriter, etc to no avail. Any suggestion appreciated.
final String boundary = "==================";
final String mimeType = "image/jpeg";
final int IMAGE_QUALITY = 100;
URL url = null;
HttpURLConnection urlConnection = null;
OutputStreamWriter request = null;
String response = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true); ///
urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
urlConnection.setRequestMethod("POST");
OutputStream outputStream= urlConnection.getOutputStream();
request = new OutputStreamWriter(outputStream);
request.append("--" + boundary).append("\n");
request.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + imageFileName + "\"").append("\n\n");
request.append("Content-Type: " + mimeType).append("\n\n");
request.append("Content-Encoding: base64").append("\n\n");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
imageThumbnail.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, stream);
byte[] byteArray = stream.toByteArray();
//request.append(new String(byteArray)).append("\n");
String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
request.append(encodedImage);
request.append("--" + boundary + "--");
request.flush();
request.close();
String line = null;
InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
response = sb.toString(); // = "Success"
isr.close();
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
response = "Malformed URL";
} catch (IOException e) {
e.printStackTrace();
response = "IO Exception";
}
return response;
Thanks to this post here, solution is as follows:
final String boundary = "==================";
final String twoHyphens = "--";
final String crlf = "\r\n";
final String mimeType = "image/jpeg";
final int IMAGE_QUALITY = 100;
URL url = null;
HttpURLConnection urlConnection = null;
DataOutputStream dos;
String response = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true); ///
urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
//urlConnection.setRequestProperty("Content-Type", "image/jpeg");
urlConnection.setRequestMethod("POST");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
imageThumbnail.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, stream);
byte[] byteArray = stream.toByteArray();
dos = new DataOutputStream(urlConnection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + crlf);
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + imageFileName + "\"" + crlf);
dos.writeBytes("Content-Type: " + mimeType + crlf);
dos.writeBytes(crlf);
dos.write(byteArray);
dos.writeBytes(crlf);
dos.writeBytes(twoHyphens + boundary + twoHyphens);
dos.flush();
dos.close();
String line = null;
InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
response = sb.toString();
isr.close();
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
response = "Malformed URL";
} catch (IOException e) {
e.printStackTrace();
response = "IO Exception";
}
return response;
I have these inside the #Override protected String doInBackground(String... params) of an AsyncTask<String, Void, String>
Related
I need to fetch data from this site http://www.speech.cs.cmu.edu/cgi-bin/tools/lmtool/run
But I am getting this "[ERRO] Problems with your corpus; cannot continue. Please check diagnostics [0 0]" When I am trying to send text file to site.
Here is my code:
String fileUrl = "/sdcard/fish.txt";
File logFileToUpload = new File(fileUrl);
final String BOUNDERY = "------WebKitFormBoundary4Pn8WfAaV8Bv3qqy";
final String CRLF = "\r\n";
// MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
StringBuilder sbBody_1 = new StringBuilder();
sbBody_1.append(BOUNDERY + CRLF);
sbBody_1.append("Content-Disposition: form-data; name=\"formtype\"" + CRLF);
sbBody_1.append(CRLF);
sbBody_1.append("simple");
sbBody_1.append(BOUNDERY + CRLF);
sbBody_1.append("Content-Disposition: form-data; name =\"corpus\""+"filename=\"fish\"" + CRLF);
//sbBody_1.append("Content-Disposition: form-data; filename=\"fish\"" + CRLF);
String str1="aaa";
sbBody_1.append(CRLF);
//sbBody_1.append(str1);
//sbBody_1.append(CRLF);
//sbBody_1.append(BOUNDERY + "--" );
StringBuilder sbBody_2 = new StringBuilder();
//sbBody_2.append("pratik");
sbBody_2.append(BOUNDERY + "--" );
URL url = new URL("http://www.speech.cs.cmu.edu/cgi-bin/tools/lmtool/run");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
// connection.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary4Pn8WfAaV8Bv3qqy");
// connection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(connection.getOutputStream());
out.write(sbBody_1.toString().getBytes());
//byte[] bFile = new String(getBytesFromFile(Files1)).getBytes();
// System.out.println(""+bFile);
FileInputStream inputStreamToLogFile = new FileInputStream(logFileToUpload);
int bytesRead;
byte[] dataBuffer = new byte[1024];
while((bytesRead = inputStreamToLogFile.read(dataBuffer)) != -1) {
out.write(dataBuffer, 0, bytesRead);
System.out.println("output"+dataBuffer +bytesRead);
}
out.write(sbBody_2.toString().getBytes());
//out.write(CRLF.getBytes());
out.flush();
out.close();
BufferedReader bips = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String temp = null;
while ((temp = bips.readLine()) != null) {
System.out.println("output"+temp);
((TextView) findViewById(R.id.textview1))
.setText(temp);
}
bips.close();
connection.disconnect();
It's better to use OkHttp for network requests. You can try this example for multipart request.
Thank you for your help #MaxV i sloved my issue by using OkHttp and POSTMAN
i'm trying to send some data to a server. The server is waiting a json and an image. I tried with every example that i found but i couldn't send the data. Actually i'm sending the json params with a PrintWriter object, but it doesn't accept the image. I need to use HttpURLConnection not with the apache library. This is my piece of code working:
HttpURLConnection connection = null;
PrintWriter output = null;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
attachImage.compress(Bitmap.CompressFormat.PNG, 40, stream);
byte[] imageData = stream.toByteArray();
String imagebase64 = Base64.encodeToString(imageData, Base64.DEFAULT);
Log.d(tag, "POST to " + url);
try{
URL url = new URL(this.url);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty(HTTP_CONTENT_TYPE, "application/json; charset=utf-8");
connection.setRequestProperty(HTTP_USER_AGENT, mUserAgent);
connection.setRequestProperty(HTTP_HEADER_ACCEPT, "application/json; charset=utf-8");
connection.connect();
output = new PrintWriter(connection.getOutputStream());
JSONObject jsonParam = new JSONObject();
jsonParam.put("oauth_token", params.get("oauth_token"));
jsonParam.put("rating", "1");
jsonParam.put("comments", "ASDASDASDASDASDASDAS");
Log.d(tag, jsonParam.toString());
output.print(jsonParam);
output.flush();
output.close();
Log.d(tag, connection.getResponseCode() + connection.getResponseMessage());
}catch(Exception e ){
}
When I try to send an image in json params, I receive an 500 internal error message.
Thanks!
Okay , as per my suggestion 2 ways to send image to server
use base 64 string
Direct upload to server
1.for base 64 go to below link
Android post Base64 String to PHP
2.for direct upload to server Please check below link
http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/
Happy coding !!
People! After a lot of day, i could upload an image to a server! I was reading this library, which is for a lot of uses. https://source.android.com/reference/com/android/tradefed/util/net/HttpMultipartPost.html
I downloaded the source code, and i took some clases to send an image. I send only bytes, which were encoded from ASCII. Thanks for the help!
Check this below code to send form data and zip file containing images or other any media files.
private class MultipartFormTask extends AsyncTask<String, Void, String> {
String getStringFromInputStream(HttpURLConnection conn) {
String strResponse = "";
try {
DataInputStream inStream = new DataInputStream(
conn.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(
inStream));
String line;
while ((line = br.readLine()) != null) {
strResponse += line;
}
br.close();
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
return strResponse;
}
void uploadJSONFeed(HttpURLConnection conn, DataOutputStream dos,
String lineEnd) {
String issue_details_key = "issue_details";
String issue_details_value = "Place your Jsondata HERE";
try {
dos.writeBytes("Content-Disposition: form-data; name=\""
+ issue_details_key + "\"" + lineEnd
+ "Content-Type: application/json" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(issue_details_value);
dos.writeBytes(lineEnd);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
}
void uploadZipFile(HttpURLConnection conn, DataOutputStream dos,
String lineEnd) {
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
InputStream is = null;
try {
is = getAssets().open("Test.zip");
} catch (IOException ioe) {
// TODO Auto-generated catch block
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
String zip_file_name_key = "file_zip";
String upload_file_name = "test.zip";
dos.writeBytes("Content-Disposition: form-data; name=\""
+ zip_file_name_key + "\";filename=\""
+ upload_file_name + "\"" + lineEnd); // uploaded_file_name
// is the Name
// of the File
// to be
// uploaded
dos.writeBytes(lineEnd);
bytesAvailable = is.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = is.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = is.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = is.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
is.close();
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String urlString = "http://www.example.org/api/file.php";
try {
// ------------------ CLIENT REQUEST
// FileInputStream fileInputStream = new FileInputStream(new
// File(existingFileName) );
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
uploadJSONFeed(conn, dos, lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
uploadZipFile(conn, dos, lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
// ------------------ read the SERVER RESPONSE
String strResponse = getStringFromInputStream(conn);
return strResponse;
}
#Override
protected void onPostExecute(String result) {
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
.show();
Log.e("Result:", result);
}
}
you can upload large jsonstring using buffer please use bellow code .
HttpsURLConnection connection = null;
OutputStream os = null;
InputStream is = null;
InputStreamReader isr = null;
try {
connection = (HttpsURLConnection) url.openConnection();
SSLContext contextSSL = SSLContext.getInstance("TLS");
contextSSL.init(null, new TrustManager[]{new DefaultTrustManager()}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(contextSSL.getSocketFactory());
MySSLFactory(context.getSocketFactory()));
HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(0);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Authorization", auth);
connection.setConnectTimeout(timeoutMillis);
OutputStream os ;
if (input != null && !input.isEmpty()) {
os = connection.getOutputStream();
InputStream stream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8));
BufferedInputStream bis = new BufferedInputStream(stream, 8 * 1024);
byte[] buffer = new byte[8192];
int availableByte = 0;
while ((availableByte = bis.read(buffer)) != -1) {
os.write(buffer, 0, availableByte);
os.flush();
}
}
int responseCode = connection.getResponseCode();
HTTP 500 error code means a server-side error occured.
This has nothing to do with your code.
The server is having a bug, not your code.
I ran into a problem while trying to send some binary files(a 1.44 MB video and a png Image) along with some string params by using multipart-form. The problem is that after writing the headers and all the necessary stuff , when writing bytes on outputstream it blocks me from writing something else .
Can you please tell me what am i doing wrong !!
Here is my AsyncTask that sends data to the server
private class UploadUpAsyncTask extends AsyncTask<String, Void,
String>{
private String path;
private String lineend ="\r\n";
private String boundry = "****";
private String twoHiphens="--";
int bytesRead,bytesAvailable,bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
public UploadUpAsyncTask(String path){
this.path =path;
}
#Override
protected String doInBackground(String... urls) {
File file = new File(path);
File image = new File("/storage/emulated/0/DCIM/100MEDIA/error.png");
try {
URL url = new URL(urls[0]);
Log.d("UPLOAD", "URL ="+urls[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundry);
conn.setRequestProperty("Authorization", "----------------------------");
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"user_id\""+lineend+lineend);
out.writeBytes("1"+lineend);
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"preview_id\""+lineend+lineend);
out.writeBytes("1"+lineend);
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"categories_id\""+lineend+lineend);
out.writeBytes("2"+lineend);
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"title\""+lineend+lineend);
out.writeBytes("Mama"+lineend);
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"tags\""+lineend+lineend);
out.writeBytes("mama"+lineend);
out.flush();
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"video\"; filename=\""+file.getName()+"\""+lineend);
out.writeBytes(lineend);
Log.d("UPLOAD", "Titlul video-ului ="+file.getName());
//decoding of bytes from video
FileInputStream file_stream = new FileInputStream(file);
bytesAvailable =file_stream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
buffer = new byte[bufferSize];
Log.d("UPLOAD", "Bytes Read Video =" +bytesRead);
bytesRead = file_stream.read(buffer);
//writting to outputstream
while (bytesRead >0){
out.write(buffer, 0, bytesRead);
bytesRead=file_stream.read(buffer);
}
Log.d("UPLOAD", "Done Loading first buffer");
file_stream.close();
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"thumb\"; filename=\""+image.getName()+"\""+lineend);
out.writeBytes(lineend);
Log.d("UPLOAD", "Titlul preview-ului ="+image.getName());
//decodint image bytes
FileInputStream image_stream = new FileInputStream(image);
int bytesRead2;
int bytesAvailable2, bufferSize2 ;
bytesAvailable2 = image_stream.available();
bufferSize2 = Math.min(bytesAvailable2, maxBufferSize);
byte []buffer2 = new byte[bufferSize2];
//writing to outputstream
bytesRead2 = image_stream.read(buffer2);
while(bytesRead2>0){
out.write(buffer2, 0, bytesRead2); // bytesAvailable2 = image_stream.available();
bytesRead2 = image_stream.read(buffer2);
}
image_stream.close();
Log.d("UPLOAD", "Done loading the second buffer");
out.writeBytes(twoHiphens+boundry+twoHiphens+lineend);
out.writeBytes(lineend);
out.flush();
out.close();
Log.d("UPLOAD","Response Code = "+conn.getResponseCode());
String responseMessage = conn.getResponseMessage();
Log.d("UPLOAD", "Response Message = "+responseMessage);
InputStream in;
if(conn.getResponseCode() >= 400){
in = conn.getErrorStream();
}else{
in = conn.getInputStream();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
StringBuilder response = new StringBuilder();
char []bytes = new char[512];
int read ;
while((read = reader.read(bytes))!=-1){
response.append(bytes, 0, read);
}
Log.d("UPLOAD", "Response " +response);
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "maine";
}
#Override protected void onPostExecute(String result) {
super.onPostExecute(result); Log.d("UPLOAD", "Upload complete");
}
}
SOLVED !! The MIME Type selection of the files sent on the server was all wrong !
This is the REST Api for uploading a document
Request URL
http:upload_url/{userid}/file
Method Type
POST
Header
Content-Type:application/json
Url Variables
1.{userid} - Unique id of the logged in user (e.g. VB000V)
form-data
{
key: "file",value: ,type: "file"
key: "filepath",value: "",type: "text"}
Code:
public class HttpUploadDoc extends AsyncTask<File, Void, String>{
private HttpClient client;
private HttpPost post;
private HttpResponse response;
private HttpEntity entity;
private ProgressDialog mProgressDialog;
private SharedPreferences sharedPreferences;
int serverResponseCode=0;
//for uploading..//
String end = "\r\n";
String twoHyphens = "--";
String boundary = "******";
private Context con;
StringBuffer buffer=new StringBuffer();
public HttpUploadDoc(Context con){
this.con=con;
}
#Override
protected void onPreExecute() {
mProgressDialog=new ProgressDialog(con);
mProgressDialog.setMessage("Loading");
mProgressDialog.show();
super.onPreExecute();
}
protected String doInBackground(File... params) {
File file=params[0];
String path=file.getAbsolutePath();
FileBody fileBody=new FileBody(file);
sharedPreferences=con.getSharedPreferences("LoginPref",Context.MODE_PRIVATE);
String userId=sharedPreferences.getString("userid", "");
client=new DefaultHttpClient();
try {
String filename=path.substring(path.lastIndexOf("/")+1);
URL url = new URL(AllRestApiUrls.UploadDocument+userId+"/file");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setChunkedStreamingMode(128 * 1024);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type", "application/pdf");
httpURLConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
httpURLConnection.setRequestProperty("file",filename);
httpURLConnection.setRequestProperty("filepath", path);
DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
String formdata="key=\"file\", value=\""
+ filen+"\""+end
+"key=\"filepath\",value=\""+path+"\"";
dos.writeBytes(twoHyphens + boundary + end);
dos.writeBytes("Content-Disposition: form-data; "+formdata);
dos.writeBytes(end);
FileInputStream fis = new FileInputStream(path);
int bufferSize = 8 * 1024; // The size of the buffer, 8KB.
byte[] buffer = new byte[bufferSize];
int length = 0;
while ((length = fis.read(buffer)) != -1) {
// Write data to DataOutputStream
dos.write(buffer, 0, length);
}
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
fis.close(); // Close the FileInputStream.
dos.flush(); // Flush the data to DataOutputStream.
serverResponseCode = httpURLConnection.getResponseCode();
String serverResponseMessage = httpURLConnection.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
entity.addPart("file", fileBody);
FileInputStream input=new FileInputStream(f.getPath());
entity.addPart("filepath", new StringBody(f.getAbsolutePath()));
post.setEntity(entity);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(f);
intent.setDataAndType(uri, "application/pdf");
con.startActivity(intent);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mProgressDialog.dismiss();
return null;
}
}
I am sending a image to webserver using following code. and in string viewstate i get "/wEPDwUKLTQwMjY2MDA0M2RkXtxyHItfb0ALigfUBOEHb/mYssynfUoTDJNZt/K8pDs=" as a response. But I want the URL . How Can I achieve this.
#Override
protected String doInBackground(String... params) {
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] image=stream.toByteArray();
//System.out.println("byte array:"+image);
String img_str = Base64.encodeToString(image, 0);
//System.out.println("string:"+img_str);
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "********";
String response = "";
int maxBufferSize = 1*1024*1024;
String mimeType = "image/jpeg";
URL url;
try {
url = new URL("url");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
//conn.setChunkedStreamingMode(0);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
DataOutputStream dos;
dos = new DataOutputStream(conn.getOutputStream());
// dos.writeBytes("Content-Disposition: form-data; name=\"__VIEWSTATE\"\r\n\r\n" );
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + img_str +"\"" + lineEnd);
dos.writeBytes(lineEnd);
//FileInputStream fileInputStream = new FileInputStream(img_str);
InputStream is = conn.getInputStream();
// retrieve the response from server
int ch;
StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
s=b.toString();
Log.i("Response",s);
dos.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
#Override
protected void onPostExecute(String s) {
int i = 0;
String viewstate = "";
while (true){
int found = s.indexOf("\"__VIEWSTATE\"", i);
if (found == -1) break;
int start = found + 38; //check numbers from start of "__V"
int end = (s.indexOf("/>", start)) -2;
viewstate = s.substring(start, end);
i = end + 1;
Log.e("VIEW STATE", viewstate);
StringBuilder builder=new StringBuilder();
builder.append(image);
builder.append(viewstate);
String a= builder.toString();
System.out.println(a);
super.onPostExecute(s);
}
Could you post an example URL please?
Edit: int found = s.indexOf("\"__VIEWSTATE\"", i); returns the index of the first matched pattern. So if you wan't to get the url, you should use viewstate = s.substring(0, found);