I am trying to send a POST request with some String parameters and a jpeg image file. The whole code is in an IntentService.
I am using an Authorization header for the basic auth (the credentials work when using them with another web service).
I can't really get what is wrong, maybe a faulty request property. Keep in mind that I am sending Strings, but also an image.
int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; try { FileInputStream fileInputStream = new FileInputStream(new File(filePath)); URL url = new URL(urlServer); String credentials = "[email protected]"+":"+"testtest"; final String basicAuth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", basicAuth); connection.setRequestProperty("Content-Type", "multipart/form-data"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setInstanceFollowRedirects(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes("imei="+ getImei() + "&id=38" + "&type = b" + "&step=1" + "&image=" ); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; int sentBytes = 0; bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { mBuilder.setProgress(100,(int) (sentBytes * 100 / bytesAvailable),false); mNotifyManager.notify(1, mBuilder.build()); outputStream.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); sentBytes += bufferSize; bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } mBuilder.setContentText("Upload complete"); mBuilder.setProgress(0, 0, false); mNotifyManager.notify(1, mBuilder.build()); fileInputStream.close(); outputStream.flush(); outputStream.close(); if(connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP){ url = new URL(connection.getHeaderField("Location")); connection = (HttpURLConnection)url.openConnection(); connection.setRequestProperty("Authorization", basicAuth); } InputStreamReader isr = null; BufferedReader reader = null; StringBuilder sb = new StringBuilder(); String line = ""; isr = new InputStreamReader( connection.getInputStream()); reader = new BufferedReader(isr); line = reader.readLine(); while (line != null) { sb.append(line); try { line = reader.readLine(); }catch (Exception e){ line = null; } } String a; a = sb.toString(); } catch (Exception ex) { ex.printStackTrace(); }