I want to post three string fields with one image i have tried below code its working without images
Below method i calling asyntask in doInBackground
private void fileUpload() {
Log.e("file_upl","file_upl started");
int serverResponse;
Bitmap b = BitmapFactory.decodeFile("/sdcard/screen_shot.png");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 0, baos);
try {
HttpClientcreaed client = new HttpClientcreaed(url+"/api/v1/screens/screenshot_upload/");
HashMap<String,Object> hashMap_post = new HashMap<>();
hashMap_post.put("device_id",deviceId);
hashMap_post.put("random_number",randomNumber);
hashMap_post.put("type","scrnshot");
hashMap_post.put("file", baos.toByteArray()); //i think here
// is problem how to sent image bye...without image its working
serverResponse = client.connectForMultipart(hashMap_post);
Log.e("checkingresponceresults","&&&& "+serverResponse);
}
catch(Throwable t) {
t.printStackTrace();
Log.e("exception","excep " + t.toString());
}
}
This is the method is inside Httpcliendcread class i calling
public int connectForMultipart(HashMap<String,Object> postDataParams) throws Exception {
con = (HttpURLConnection) (new URL(url)).openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty("Connection", "Keep-Alive"); //application/x-www-form-urlencoded
//con.setRequestProperty("Content-Type", "multipart/x-www-form-urlencoded; boundary=" + boundary);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream os = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
String response = "";
if ( con.getResponseCode() == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
Log.e("responchecking","&&&& "+response);
return con.getResponseCode();
/* con.connect();
os = con.getOutputStream();*/
}
This is another method for append the url
private String getPostDataString(HashMap<String, Object> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, Object> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode((String) entry.getValue(), "UTF-8"));
}
return result.toString();
}
I have searched google but i didnot getting any solution...
I checked postman its working
below is error:
excep java.lang.ClassCastException: byte[] cannot be cast to java.lang.String
Thanks in advance