java.net.SocketException:上传文件到restful wcf(Web服务)时管道是否损坏?

时间:2012-06-27 07:43:27

标签: android wcf rest broken-pipe

我正在破坏piper错误 日志是:

06-27 12:45:49.144: E/Debug(2526): error: Broken pipe
06-27 12:45:49.144: E/Debug(2526): java.net.SocketException: Broken pipe
06-27 12:45:49.144: E/Debug(2526):  at org.apache.harmony.luni.platform.OSNetworkSystem.write(Native Method)
06-27 12:45:49.144: E/Debug(2526):  at dalvik.system.BlockGuard$WrappedNetworkSystem.write(BlockGuard.java:284)
06-27 12:45:49.144: E/Debug(2526):  at org.apache.harmony.luni.net.PlainSocketImpl.write(PlainSocketImpl.java:472)
06-27 12:45:49.144: E/Debug(2526):  at org.apache.harmony.luni.net.SocketOutputStream.write(SocketOutputStream.java:57)
06-27 12:45:49.144: E/Debug(2526):  at org.apache.harmony.luni.internal.net.www.protocol.http.FixedLengthOutputStream.write(FixedLengthOutputStream.java:40)
06-27 12:45:49.144: E/Debug(2526):  at java.io.DataOutputStream.write(DataOutputStream.java:99)
06-27 12:45:49.144: E/Debug(2526):  at org.awarebase.tina.mobile.ui.ObjectDescriptionActivity$CheckInAsync.doInBackground(ObjectDescriptionActivity.java:903)
06-27 12:45:49.144: E/Debug(2526):  at org.awarebase.tina.mobile.ui.ObjectDescriptionActivity$CheckInAsync.doInBackground(ObjectDescriptionActivity.java:1)
06-27 12:45:49.144: E/Debug(2526):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
06-27 12:45:49.144: E/Debug(2526):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
06-27 12:45:49.144: E/Debug(2526):  at java.util.concurrent.FutureTask.run(FutureTask.java:138)
06-27 12:45:49.144: E/Debug(2526):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
06-27 12:45:49.144: E/Debug(2526):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
06-27 12:45:49.144: E/Debug(2526):  at java.lang.Thread.run(Thread.java:1019)

上传文件的Android Async任务是:

class CheckInAsync extends AsyncTask<String, String, String> {

            HttpEntity responseEntity = null;

            OutputStream mystream;

            String resposeCheckin = new String();
            String existingFileName = "/mnt/sdcard/abtemp/" + objrid
                    + fileExtension;
            private Activity context;
            private FragmentManager fmgr;

            public void updateActivity(Activity c, FragmentManager fm) {
                context = c;
                fmgr = fm;
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                File direct = new File(Environment.getExternalStorageDirectory()
                        + "/abtemp");

                if (!direct.exists()) {
                    if (direct.mkdir())
                        ; // directory is created;
                    existingFileName = "/mnt/sdcard/abtemp/" + objrid
                            + fileExtension;// add "." to make file or folder hidden
                }
                if (isOnline(ObjectDescriptionActivity.this).equals("false")) {
                    Toast.makeText(getBaseContext(), "no Internet Connection",
                            Toast.LENGTH_LONG).show();
                } else {
                    ProgressDialogFragment po = new ProgressDialogFragment(
                            CheckInAsync.this);

                    FragmentTransaction fragmentTransaction = fmgr
                            .beginTransaction();
                    po.show(fragmentTransaction, "DIALOG_F3");

                }
            }

            @Override
            protected String doInBackground(String... param) {
                if ((isOnline(ObjectDescriptionActivity.this).equals("true"))) {
                    try {



                        URL url = null;
                        HttpURLConnection conn = null;
                        DataOutputStream dos = null;
                        DataInputStream inStream = null;

                        StringBuffer sb;

                        int bytesRead, bytesAvailable;

                        int maxBufferSize = Integer.MAX_VALUE;
                        try {


                            url = new URL(
                                    getResources().getString(R.string.ServiceBaseUrl)+"ServiceMobile.svc/Service/uploadRequestMobile?"+
                                            "userName="                                     
                                            + param[0]
                                            + "&clientname="
                                            + param[2]
                                            + "&password="
                                            + param[1]
                                            + "&filename="
                                            + param[4]
                                            + "&fileExtension="
                                            + param[5]
                                            + "&objrid=" + param[3]);
                            // 
                        } catch (MalformedURLException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        System.gc();

                        try {
                            // ------------------ CLIENT REQUEST
                            File file = new File(existingFileName);

                            if (file.isFile()) {
                                FileInputStream fileInputStream = new FileInputStream(
                                        file);



                                //
                                // Open a HTTP connection to the URL
                                conn = (HttpURLConnection) url.openConnection();
                                // Allow Inputs
                                conn.setDoInput(true);
                                // Allow Outputs
                                conn.setDoOutput(true);
                                // Don't use a cached copy.
                                conn.setUseCaches(false);
                                // Use a post method.
                                conn.setRequestMethod("POST");                      

                                maxBufferSize = 6 * 1024;




            conn.setFixedLengthStreamingMode((int) file.length());// works fine till 24 mb file
                                conn.setRequestProperty("Connection", "Keep-Alive");
                                conn.setRequestProperty("Content-Type",
                                        "application/stream");

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

                                bytesAvailable = fileInputStream.available();
                                int bufferSize = Math.min(bytesAvailable,
                                        maxBufferSize);
                                bytesAvailable = fileInputStream.available();

                                bufferSize = Math
                                        .min(bytesAvailable, maxBufferSize);

                                byte[] buffer = new byte[bufferSize];


                                bytesAvailable = fileInputStream.available();
                                int downloadedSize = 0;
                                while ((bufferSize = fileInputStream.read(buffer)) > 0) {

                                    dos.write(buffer, 0, bufferSize);

                                    downloadedSize += bufferSize;
                                    publishProgress(""
                                            + (int) ((downloadedSize * 100) / bytesAvailable));
                                e

                                }
                                String lineEnd = "";

                                dos.writeBytes(lineEnd);


                                fileInputStream.close();
                                dos.flush();
                                dos.close();
                            } else {
                                return "file not found";
                            }
                        } catch (MalformedURLException ex) {
                            Log.e("Debug", "error: " + ex.getMessage(), ex);
                        } catch (IOException ioe) {
                            Log.e("Debug", "error: " + ioe.getMessage(), ioe);
                        }
                        // ------------------ read the SERVER RESPONSE
                        try {
                            inStream = new DataInputStream(conn.getInputStream());
                            String str = new String();
                            sb = new StringBuffer(str);
                            while ((str = inStream.readLine()) != null) {
                                sb.append(str);


                            }
                            inStream.close();
                 Log.e("Debug","Server Response "+sb.toString());
                            resposeCheckin = new String(sb);

                        }

                        catch (IOException e) {

                            resposeCheckin = "UnSuccess";
                             e.printStackTrace();
                        }

                        String str_raj = resposeCheckin.substring(1,
                                resposeCheckin.length() - 1);

                        Log.e("hhguyuyjjhyjhjyhjhjhjh", str_raj);

                        return str_raj;

                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                        return "Sorry,Illegal state error";
                    } 
                }
                return null;

            }

            protected void onProgressUpdate(String... progress) {
                ProgressDialogFragment d1 = (ProgressDialogFragment) fmgr
                        .findFragmentByTag("DIALOG_F3");
                d1.dialog
                        .setMessage("Uploading File....  "
                                + CommenUtil.Round((Float.parseFloat(progress[0])
                                        * filesize / (100 * 1024 * 1024)), 2)
                                + "MB of "
                                + CommenUtil.Round(
                                        ((new Integer((int) filesize).floatValue()) / (1024 * 1024)),
                                        2) + " MB");
                d1.dialog.setProgress(Integer.parseInt(progress[0]));

            }

            @Override
            protected void onPostExecute(String responsestr) {
                ProgressDialogFragment d1 = (ProgressDialogFragment) fmgr
                        .findFragmentByTag("DIALOG_F3");
                d1.dismiss();
                Log.e("in post execute", responsestr);
                int objrid = -1;
                if (responsestr.equals("exception") == false) {
                    try {
                        objrid = Integer.parseInt(responsestr);

                        Log.e("my integer", "my integer value " + objrid);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                        if (responsestr == null
                                || responsestr.equalsIgnoreCase("UnSuccess")
                                || responsestr.equalsIgnoreCase("null")
                                || responsestr.equalsIgnoreCase("0")
                                || responsestr.equalsIgnoreCase("Exception")
                                || responsestr.equalsIgnoreCase("file not found")) {
                            Toast.makeText(ObjectDescriptionActivity.this,
                                    "Checkin UnSuccessful ::  " + responsestr,
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(
                                    getBaseContext(),
                                    "Exception in background task message is"
                                            + responsestr, Toast.LENGTH_LONG)
                                    .show();
                        }
                    }
                    if (objrid >= 0) {
                        if (isOnline(ObjectDescriptionActivity.this).equals("true")) {

                            File file = new File(existingFileName);
                            file.delete();
                            file.list();
                            isLock = "false";
                            File file_data = new File(
                                    "/data/data/org.awarebase.tina.mobile/databases/Myobject.db");
                            file_data.delete();
                            Toast.makeText(
                                    ObjectDescriptionActivity.this,
                                    "Checkin Successful :"
                                            + "New object Rid is::  " + responsestr,
                                    Toast.LENGTH_SHORT).show();
                            Log.e("system", "is before sleep mode");

                            Log.e("system", "is sleep mode");
                            Intent myObjects_Intent = new Intent(ObjectDescriptionActivity.this,MyObjectsActivity.class);
                            startActivity(myObjects_Intent);

                        }

                    }
                } else {
                    Toast.makeText(ObjectDescriptionActivity.this, "exception",
                            Toast.LENGTH_SHORT).show();
                }
            }
        }

.net wcf要上传的代码:

public string uploadRequestMobile(string userName, string clientname, string password, string filename, string fileExtension, long objrid, Stream data)
       {
           MobileClientEntity clientEntity = new MobileClientEntity();
           clientEntity.ClientName = clientname;
           clientEntity.UserName = userName;
           clientEntity.Password = password;


           LoadMetaDataService objLoadMetaData = new LoadMetaDataService();
           Membership.ApplicationName = clientEntity.ClientName;
           MessageType status = MessageType.None;
           string GuId;
           if (Membership.ValidateUser(clientEntity.UserName, clientEntity.Password))
           {
               UserProfileService obj_userprofile_Service = new UserProfileService();
               GuId = obj_userprofile_Service.GetGuid(clientEntity.ClientName, clientEntity.UserName, out status);
               if (status == MessageType.Error && GuId == null)
               {
                   return null;
               }
               UserProfileEntity objUser = obj_userprofile_Service.GetUserInfo(GuId, clientEntity.ClientName, out status);
               if (status == MessageType.Error)
               {
                   return null;
               }

               MessageType status2 = MessageType.None;



               try
               {
                   byte[] bytedata;
                   byte[] buffer = new byte[6 * 1024];
                   using (MemoryStream ms = new MemoryStream())
                   {
                       int read;
                       while ((read = data.Read(buffer, 0, buffer.Length)) > 0)
                       {
                           ms.Write(buffer, 0, read);
                       }
                       bytedata= ms.ToArray();
                   }



                   bool IsAdmin = false;  

                   ObjectEntity objDocumentObjectEntity = objLoadMetaData.LoadMetaDataMobile(clientEntity, objrid);
                   DocumentManagementEntity objDocumentMgmtEntity = new DocumentManagementEntity();
                   if (objUser.ObjectRid == objDocumentObjectEntity.OwnerRid)
                   {
                       objDocumentMgmtEntity.IsOwner = true;
                   }
                   if (bytedata != null)
                   {
                       objDocumentMgmtEntity.ObjRid = objrid;
                       objDocumentMgmtEntity.ObjThd = objrid;
                       objDocumentMgmtEntity.ClassIcon = null;
                       objDocumentMgmtEntity.CheckinFileName = filename;
                       objDocumentMgmtEntity.FileData = bytedata;
                       objDocumentMgmtEntity.FileExtension = fileExtension; // will be get from android client as new file name and extention
                       objDocumentMgmtEntity.FileName = filename;
                       objDocumentMgmtEntity.FunctionName = "SaveMetaData";
                       objDocumentMgmtEntity.FileSize = bytedata.Length;
                       objDocumentMgmtEntity.ObjEntity = new ObjectEntity();
                       objDocumentMgmtEntity.ObjEntity.Description1 = objDocumentObjectEntity.Description1;
                       objDocumentMgmtEntity.ObjEntity.Description2 = objDocumentObjectEntity.Description2;
                       objDocumentMgmtEntity.ObjEntity.FileExt = fileExtension;
                       objDocumentMgmtEntity.ObjEntity.FileName = filename;
                       objDocumentMgmtEntity.ObjEntity.ObjectRid = objrid;
                       objDocumentMgmtEntity.ObjEntity.ObjectThread = objrid;
                       objDocumentMgmtEntity.ObjEntity.OwnerRid = objDocumentObjectEntity.OwnerRid;
                       objDocumentMgmtEntity.ObjRid = objrid;
                       objDocumentMgmtEntity.ObjThd = objrid;
                       objDocumentMgmtEntity.UsrRid = objUser.ObjectRid;

                       long newobjrid = new DocumentManagementService().ProcessCheckinRequest(objDocumentMgmtEntity, clientEntity.ClientName, out status2);
                       if (status2 == MessageType.Success)
                           return newobjrid.ToString();

                   }
               }

               catch (Exception ex)
               {

                   return ex.Message;
               }
           }

           return "UnSuccess";

       }

我已经尝试了所有的事情,请指导。一段时间相同的代码工作正常,有时它会丢失管道错误。

1 个答案:

答案 0 :(得分:1)

问题出在网址上。 我在网址发送一些文件名。但是每当文件名包含空格时,它就会变成一个错误的URL,在这种情况下它会丢失管道错误。