Exception while accessing servlet using HttpUrlConnection
<p>I need to upload an image to a server. For that i need to pass 2 parameters </p>

<p><strong>1. image(byte array)<br>
2. ID(id of the user)</strong></p>

<p>How can i pass parameters for a POSt method using Http Url COnnection </p>

<p>Here i tried to pass the byte arry(image) part by part .</p>

<p>But when i exceute the code an excpetion is thrown:  </p>

<p>My code is : </p>

<pre><code>ByteArrayOutputStream out = new ByteArrayOutputStream();
bmp.compress(CompressFormat.PNG, 100, out);
byte[] imageBytes = out.toByteArray();
String imagePost = Base64.encodeToString(imageBytes, Base64.DEFAULT);

String fileName = "temporary_holder.jpg";
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String responseFromServer = "";
String sourceFileUri = HomeScreen.get_path();

String upLoadServerUri = "http://10.120.10.87:8080/ContactsManagerWeb/CustomHttpRequest";

File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
                return;
}
int serverResponseCode = 0;
try { // open a URL connection to the Servlet
    FileInputStream fileInputStream = new FileInputStream(sourceFile);
    URL url = new URL(upLoadServerUri);

    conn = (HttpURLConnection) url.openConnection(); // Open a HTTP
                         // connection to
                             // the URL
    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("Content-Type",
        "multipart/form-data;boundary=" + boundary);

    conn.setRequestProperty("userId", String.valueOf(userId));
    //conn.setRequestProperty("image", imagePost);
    conn.addRequestProperty("userId", String.valueOf(userId));

    conn.addRequestProperty("image", imagePost);

    dos = new DataOutputStream(conn.getOutputStream());

    dos.writeBytes(twoHyphens + boundary + lineEnd);
    dos.writeBytes("Content-Disposition: form-data; name=\"image\";filename=\""
        + imagePost + "\"" + lineEnd);
    dos.writeBytes(lineEnd);

    bytesAvailable = fileInputStream.available(); // create a buffer of
                          // maximum size
    System.out.println("Huzza Initial .available : " + bytesAvailable);

    // bufferSize = Math.min(bytesAvailable, maxBufferSize);
    bufferSize = (int) sourceFile.length();

    System.out.println("BytesAvail" + bytesAvailable);
    System.out.println("maxBufferSize" + maxBufferSize);
    buffer = new byte[bufferSize];

    // read file and write it into form...
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

    while (bytesRead &gt; 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 (code and message)
    serverResponseCode = conn.getResponseCode();
    String serverResponseMessage = conn.getResponseMessage();

    System.out.println("Upload file to serverHTTP Response is : "
        + serverResponseMessage + ": " + serverResponseCode);
    // close streams
    System.out.println("Upload file to server" + fileName
        + " File is written");
    fileInputStream.close();
    dos.flush();
    dos.close();
} catch (MalformedURLException ex) {
    ex.printStackTrace();
    Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
    e.printStackTrace();
}
// this block will give the response of upload link
try {
    BufferedReader rd = new BufferedReader(new InputStreamReader(
        conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
    System.out.println("" + "Message: " + line);
    }
    rd.close();
} catch (IOException ioex) {
    Log.e("faf", "error: " + ioex.getMessage(), ioex);
}
return;     
}
</code></pre>

<p>Exception : </p>

<pre><code>03-31 10:53:38.298: WARN/System.err(4522): java.net.SocketException: Broken pipe
03-31 10:53:38.302: WARN/System.err(4522):     at org.apache.harmony.luni.platform.OSNetworkSystem.writeSocketImpl(Native Method)
03-31 10:53:38.302: WARN/System.err(4522):     at org.apache.harmony.luni.platform.OSNetworkSystem.write(OSNetworkSystem.java:723)
03-31 10:53:38.302: WARN/System.err(4522):     at org.apache.harmony.luni.net.PlainSocketImpl.write(PlainSocketImpl.java:578)
03-31 10:53:38.302: WARN/System.err(4522):     at org.apache.harmony.luni.net.SocketOutputStream.write(SocketOutputStream.java:59)
03-31 10:53:38.302: WARN/System.err(4522):     at java.io.ByteArrayOutputStream.writeTo(ByteArrayOutputStream.java:248)
03-31 10:53:38.302: WARN/System.err(4522):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl$DefaultHttpOutputStream.flushToSocket(HttpURLConnectionImpl.java:680)
03-31 10:53:38.302: WARN/System.err(4522):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.sendRequest(HttpURLConnectionImpl.java:1336)
03-31 10:53:38.302: WARN/System.err(4522):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.doRequestInternal(HttpURLConnectionImpl.java:1656)
03-31 10:53:38.302: WARN/System.err(4522):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.doRequest(HttpURLConnectionImpl.java:1649)
03-31 10:53:38.302: WARN/System.err(4522):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:1374)
03-31 10:53:38.302: WARN/System.err(4522):     at com.ey.camera.webservice.ContactManagerWebService.webservicePhp(ContactManagerWebService.java:341)
03-31 10:53:38.302: WARN/System.err(4522):     at com.ey.camera.CameraView$4.onClick(CameraView.java:177)
03-31 10:53:38.306: WARN/System.err(4522):     at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:158)
03-31 10:53:38.306: WARN/System.err(4522):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-31 10:53:38.306: WARN/System.err(4522):     at android.os.Looper.loop(Looper.java:123)
03-31 10:53:38.306: WARN/System.err(4522):     at android.app.ActivityThread.main(ActivityThread.java:4627)
03-31 10:53:38.306: WARN/System.err(4522):     at java.lang.reflect.Method.invokeNative(Native Method)
03-31 10:53:38.306: WARN/System.err(4522):     at java.lang.reflect.Method.invoke(Method.java:521)
03-31 10:53:38.306: WARN/System.err(4522):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:871)
03-31 10:53:38.306: WARN/System.err(4522):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
03-31 10:53:38.306: WARN/System.err(4522):     at dalvik.system.NativeStart.main(Native Method)
</code></pre>

<p><strong>Servlet :</strong> </p>

<pre><code>protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doPost");
        String userId = request.getParameter("userId");
        String image = request.getParameter("image");
        System.out.println("value1: " +userId);
        System.out.println(" Image : "+image);
</code></pre>
