将图像从android studio上传到Wcf Service

时间:2017-04-26 12:27:23

标签: java c# android web-services wcf

我将图像从android studio发送到wcf服务两个代码都是正确的,当我点击sendToServer按钮时,应用程序崩溃了。我不知道我的代码有什么问题。 这是MainActivity.java的代码

public class MainActivity extends AppCompatActivity 
{
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       StrictMode.ThreadPolicy policy = new 
     StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        private static final int CAMERA_REQUEST = 1888;
        private int PICK_IMAGE_REQUEST = 1;
        public PlaceholderFragment() {
        }
        private final static String SERVICE_URI = "http://localhost:24895/WcfAndroidImageService/WcfAndroidImageService.svc";
        ImageView imageView = null;
        byte[] photoasbytearray = null;
        Photo ph = null;
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
                Bitmap photo = (Bitmap) data.getExtras().get("data");


                imageView.setImageBitmap(photo);

                //getting photo as byte array
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                photo.compress(Bitmap.CompressFormat.JPEG, 100,stream);
                photoasbytearray = stream.toByteArray();

                //give a name of the image here as date
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HHmm");
                String currentDateandTime = sdf.format(new Date());

                ph = new Photo();

                String encodedImage = Base64.encodeToString(photoasbytearray,Base64.DEFAULT);
                ph.photoasBase64=encodedImage;

                ph.photoName= currentDateandTime+".png";
            }
        }


        private void SendToServer(Photo ph2) throws UnsupportedEncodingException {
            // TODO Auto-generated method stub
            HttpPost httpPost = new HttpPost(SERVICE_URI+"LoadPhoto");

            httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
            HttpClient httpClient = new DefaultHttpClient(getHttpParameterObj(17000,17000));
            // Building the JSON object.

            com.google.gson.Gson gson = new GsonBuilder().disableHtmlEscaping().create();
            String json = gson.toJson(ph2);
            StringEntity entity = new StringEntity(json,"UTF_8");
            Log.d("WebInvoke", "data : " + json);
            httpPost.setEntity(entity);
            // Making the call.
            HttpResponse response = null;
            try
            {
                response = httpClient.execute(httpPost);

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
                Log.d("Exception",e.toString());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // Getting data from the response to see if it was a success.
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()
                        ));
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block

                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.d("IO_Exception",e.toString());
            }
            String jsonResultStr = null;
            try {
                jsonResultStr = reader.readLine();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Log.d("WebInvoke", "donnen  deger : " + jsonResultStr);
        }



        private HttpParams getHttpParameterObj(int timeOutConnection, int timeOutSocket)
        {
            HttpParams httpParameters = new BasicHttpParams();
            // Set the timeout in milliseconds until a connection is established.
            HttpConnectionParams.setConnectionTimeout(httpParameters, timeOutConnection);
            // Set the default socket timeout (SO_TIMEOUT)
            // in milliseconds which is the timeout for waiting for data.
            HttpConnectionParams.setSoTimeout(httpParameters, timeOutSocket);
            return httpParameters;
        }



        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.activity_photo, container,
                    false);
            imageView  = (ImageView)rootView.findViewById(R.id.imageView1);
            Button btnOpenCam = (Button) rootView.findViewById(R.id.btnOpenCam);
            Button btnSendServer = (Button) rootView.findViewById(R.id.btnSendServer);
            Button btnOpenImage = (Button)rootView.findViewById(R.id.openImage);

            btnOpenCam.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Start camera activity here
                    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, CAMERA_REQUEST);
                }
            });
            btnOpenImage.setOnClickListener(new View.OnClickListener() {


                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    // Show only images, no videos or anything else
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                     // Always show the chooser (if there are multiple options available)
                    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
                }
            });

            btnSendServer.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    try {
                        SendToServer(ph);
                       // Toast.makeText(getActivity(),"Image Sent to Server!", Toast.LENGTH_SHORT).show();
                        //Toast.makeText(getActivity(),"Server got the image!", Toast.LENGTH_SHORT).show();
                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            });
            return rootView;
        }
    }
}

这是Photo.java

package com.example.haier.leafclassification;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class Photo {
    public String  photoasBase64;
    public String photoName ;
}

在服务器端,这里是IWcfAndroidImageService.cs文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfAndroidPhotoServis
{
    [ServiceContract]
    public interface IWcfAndroidImageService
    {
        [OperationContract]
        [WebInvoke(Method = "POST",
                RequestFormat = WebMessageFormat.Json,
                ResponseFormat = WebMessageFormat.Json,
            // BodyStyle = WebMessageBodyStyle.Wrapped,
                UriTemplate = "LoadPhoto")]
        string LoadPhoto(Photo photo);

    }
}

这是WcfAndroidImageService.svc文件代码

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using WcfAndroidPhotoServis.Helper;

namespace WcfAndroidPhotoServis
{
    public class WcfAndroidImageService : IWcfAndroidImageService
    {

        public string LoadPhoto(Photo photo)
        {

            //get photofolder path
            string photofolderName = "LoadedPhotos";
            string photopath = "";
            photopath = System.Web.Hosting.HostingEnvironment.MapPath("~/"+photofolderName);
            //convert byte array to image
            Image _photo = ImageHelper.Base64ToImage(photo.photoasBase64);
            photopath = photopath + "/" + photo.photoName;
            //save photo to folder

            _photo.Save(photopath);
            //chech if photo saved correctlly into folder
            bool result = File.Exists(photopath);
           // string result = "Server got the image!";
            return result.ToString();
        }

    }

    [DataContract]
    public class Photo
    {
        //device id
        [DataMember]
        public string photoasBase64 { get; set; }

        [DataMember]
        public string photoName { get; set; }

    }
}

这是我在主要活动日志中收到的消息

W / System.err:org.apache.http.conn.HttpHostConnectException:拒绝与http://localhost:24895的连接

以下是主要活动日志显示的三个行号

java.lang.NullPointerException: Attempt to invoke interface method 'org.apache.http.HttpEntity org.apache.http.HttpResponse.getEntity()' on a null object reference
                      at com.example.haier.leafclassification.MainActivity$PlaceholderFragment.SendToServer(MainActivity.java:378)
                      at com.example.haier.leafclassification.MainActivity$PlaceholderFragment.access$100(MainActivity.java:293)
                      at com.example.haier.leafclassification.MainActivity$PlaceholderFragment$3.onClick(MainActivity.java:463)

并且这些行具有以下代码

Line 378: reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()
Line 293:   public static class PlaceholderFragment extends Fragment {

Line 463:   SendToServer(ph);

0 个答案:

没有答案