1

客户端代码在android中。.NET 中的服务器端代码。我在错误中遇到了损坏的管道。在这方面可以做些什么?

客户端代码 -

MainActivity.java

package com.example.imageupload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //loads the main screen.
        setContentView(R.layout.activity_main);

        // enables network calls in the UI thread.
        if( Build.VERSION.SDK_INT >= 9){
               StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
               StrictMode.setThreadPolicy(policy); 
        }

        FileInputStream fstrm;
        try {
            // reading the file from the device.
            fstrm                   =   new FileInputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"android.jpg");
            // Set your server page URL (and the file title/description)
            File file               =   new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"android.jpg");
            // For getting the file length.
            long length             =   file.length();

            HttpFileUpload hfu      =   new HttpFileUpload("http://10.0.2.2:49246/WebSite1", "title","description",length,fstrm);

            //Network operations shouldn't be done in the UI thread.
            Thread myThread         =   new Thread(hfu);
            myThread.start();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } 
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

HttpFileUpload.java

package com.example.imageupload;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.util.Log;

public class HttpFileUpload implements Runnable{
        URL connectURL;
        String responseString;
        String Title;
        String Description;
        Long mLength;
        byte[] dataToServer;
        FileInputStream fileInputStream = null;

        HttpFileUpload(String urlString, String vTitle, String vDesc,long length,FileInputStream fstrm){
                try{
                        connectURL      =   new URL(urlString);
                        Title           =   vTitle;
                        Description     =   vDesc;
                        mLength         =   length;
                        fileInputStream =   fstrm;
                        Sending();
                }catch(Exception ex){
                    Log.i("HttpFileUpload","URL Malformatted");
                }
        }

        void Sending(){

                String iFileName    =   "android.jpg";
                String lineEnd      =   "\r\n";
                String twoHyphens   =   "--";
                String boundary     =   "*****";
                String Tag          =   "fSnd";
                try
                {
                        Log.e(Tag,"Starting Http File Sending to URL");

                        // Open a HTTP connection to the URL
                        HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();

                        // Allow Inputs
                        conn.setDoInput(true);

                        // Allow Outputs
                        conn.setDoOutput(true); //Custom changed.

                        // Don't use a cached copy.
                        conn.setUseCaches(false);

                        // Use a post method.
                        conn.setRequestMethod("POST");

                        conn.setRequestProperty("connection", "Keep-Alive");

                        conn.setFixedLengthStreamingMode(new BigDecimal(mLength).intValueExact());

                        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

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

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

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

                        dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName +"\"" + lineEnd);
                        dos.writeBytes(lineEnd);

                        Log.e(Tag,"Headers are written");

                        // create a buffer of maximum size
                        int bytesAvailable  =   fileInputStream.available();

                        int maxBufferSize   =   1024;
                        int bufferSize      =   Math.min(bytesAvailable, maxBufferSize);
                        byte[ ] buffer      =   new byte[bufferSize];

                        // read file and write it into form...
                        int 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);
                        }
                        dos.writeBytes(lineEnd);
                        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                        // close streams
                        fileInputStream.close();

                        dos.flush();
                        dos.close();

                        Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));

                        InputStream is          =   conn.getInputStream();

                        // retrieve the response from server
                        int ch;

                        StringBuffer b          =   new StringBuffer();
                        while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
                        String s        =   b.toString();
                        Log.i("Response",s);
                        conn.disconnect(); //custom added

                }
                catch (MalformedURLException ex){   
                        Log.e(Tag, "URL error: " + ex.getMessage(), ex);
                }

                catch (IOException ioe){
                        Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
                }
        }
        @Override
        public void run() {
        }
}

服务器:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      string vTitle     =   "";
      string vDesc      =   "";
      string FilePath   =   Server.MapPath("save/android.jpg");        

      if (!string.IsNullOrEmpty(Request.Form["title"]))
      {
        vTitle = Request.Form["title"];
      }
      if (!string.IsNullOrEmpty(Request.Form["description"]))
      {
        vDesc = Request.Form["description"];
      }

      HttpFileCollection MyFileCollection = Request.Files;
      if (MyFileCollection.Count > 0)
      {
        // Save the File
        MyFileCollection[0].SaveAs(FilePath);
      }
    }
}

LogCat 输出:-

08-27 10:54:08.370: E/fSnd(472): Starting Http File Sending to URL
08-27 10:54:09.312: E/fSnd(472): IO error: Broken pipe
08-27 10:54:09.312: E/fSnd(472): java.net.SocketException: Broken pipe
08-27 10:54:09.312: E/fSnd(472):    at org.apache.harmony.luni.platform.OSNetworkSystem.write(Native Method)
08-27 10:54:09.312: E/fSnd(472):    at dalvik.system.BlockGuard$WrappedNetworkSystem.write(BlockGuard.java:291)
08-27 10:54:09.312: E/fSnd(472):    at org.apache.harmony.luni.net.PlainSocketImpl.write(PlainSocketImpl.java:462)
08-27 10:54:09.312: E/fSnd(472):    at org.apache.harmony.luni.net.SocketOutputStream.write(SocketOutputStream.java:55)
08-27 10:54:09.312: E/fSnd(472):    at org.apache.harmony.luni.internal.net.www.protocol.http.FixedLengthOutputStream.write(FixedLengthOutputStream.java:41)
08-27 10:54:09.312: E/fSnd(472):    at java.io.OutputStream.write(OutputStream.java:82)
08-27 10:54:09.312: E/fSnd(472):    at java.io.DataOutputStream.writeBytes(DataOutputStream.java:156)
08-27 10:54:09.312: E/fSnd(472):    at com.example.imageupload.HttpFileUpload.Sending(HttpFileUpload.java:78)
08-27 10:54:09.312: E/fSnd(472):    at com.example.imageupload.HttpFileUpload.<init>(HttpFileUpload.java:29)
08-27 10:54:09.312: E/fSnd(472):    at com.example.imageupload.MainActivity.onCreate(MainActivity.java:37)
08-27 10:54:09.312: E/fSnd(472):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
08-27 10:54:09.312: E/fSnd(472):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1712)
08-27 10:54:09.312: E/fSnd(472):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1764)
08-27 10:54:09.312: E/fSnd(472):    at android.app.ActivityThread.access$1500(ActivityThread.java:122)
08-27 10:54:09.312: E/fSnd(472):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1002)
08-27 10:54:09.312: E/fSnd(472):    at android.os.Handler.dispatchMessage(Handler.java:99)
08-27 10:54:09.312: E/fSnd(472):    at android.os.Looper.loop(Looper.java:132)
08-27 10:54:09.312: E/fSnd(472):    at android.app.ActivityThread.main(ActivityThread.java:4025)
08-27 10:54:09.312: E/fSnd(472):    at java.lang.reflect.Method.invokeNative(Native Method)
08-27 10:54:09.312: E/fSnd(472):    at java.lang.reflect.Method.invoke(Method.java:491)
08-27 10:54:09.312: E/fSnd(472):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
08-27 10:54:09.312: E/fSnd(472):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
08-27 10:54:09.312: E/fSnd(472):    at dalvik.system.NativeStart.main(Native Method)
4

0 回答 0