使用HttpUrlConnection访问servlet时出现异常

时间:2011-03-31 05:34:03

标签: java android

我需要将图像上传到服务器。为此,我需要传递2个参数

1。图像(字节数组)
2. ID(用户的ID)

如何使用Http Url COnnection传递POSt方法的参数

这里我试图逐个传递字节arry(图像)。

但是当我对代码表示异议时,会抛出一个重复:

我的代码是:

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 > 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;     
}

例外:

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)

Servlet:

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);

1 个答案:

答案 0 :(得分:1)

我会将输出流包装在BufferedOutputStream中,以便开始。