我将图像从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);

android studio wcf,将图像从android studio上传到Wcf Service相关推荐

  1. 简单的 Android 拍照并显示以及获取路径后上传

    简单的 Android 拍照并显示以及获取路径后上传 Activity 中的代码,我只贴出重要的事件部分代码 public void doPhoto(View view){destoryBimap() ...

  2. 新大陆物联网-Android实现网关功能-连接云平台并上传传感器数据-获取执行器指令并执行-Android网关开发-通信-数据上传云平台-JAVA原理讲解-免费云平台使用-竞赛2022国赛真题

    目录 一.任务要求 二.开发环境 三.网关上线 四.数据上传与命令下发 五.JSON命令解析思路 六.总结 一.任务要求 我们将要实现的效果是:Android开发平板与Lora板进行有线串口通信,解析 ...

  3. android使用HttpURLConnection/HttpClient实现带参数文件上传

    本文参考自[http://blog.csdn.net/crazy__chen/article/details/47703781] 在Android 2.3及以上版本,使用的是HttpURLConnec ...

  4. android上传文件用哪个布局,每周总结20130821——android控件的尺寸、http文件上传...

    Android控件的尺寸 android开发中,可以通过编写XML格式的布局文件来实现布局,也可以用纯代码进行布局,通常都是选择XML文件布局.在XML布局文件中,与控件的尺寸有关的属性有androi ...

  5. android webview使用html5input id=input type=file/ 上传相册、拍照照片

    本人编程新手,这次做的功能是android webview 嵌入HTML5的页面,页面中有一个<input id="input" type="file"/ ...

  6. Android Jenkins + gradle 实现自动化打包流程并上传至蒲公英平台全过程

    最近在windows上尝试了jenkins持续集成环境搭建,把自己的写的app进行了自动化打包上传的一套流程,下面把我的经验分享给大家. 本文大纲: 说明:本文以windows为例 环境准备 jenk ...

  7. Android 仿微信朋友圈拍小视频上传到服务器(转)

    界面是这个样子滴. 我也知不知道怎么给图片搞小一点o(╯□╰)o 布局文件是这样的[认真脸] <?xml version="1.0" encoding="utf-8 ...

  8. Android - WebView接入H5客服照片/视频上传

    webView加载H5,主要是解决上传图片和视频的问题. 1)Activity定义一些常量变量 private static final int REQUEST_CODE_PERMISSION_CAM ...

  9. 【手把手教】Android开发两种方式实现图片的上传下载

    Android 图片上传的应用场景 在Android开发中,很多时候我们需要进行图片,文件的上传下载,最直接的一个应用场景就是用户头像的保存与切换,以及像即时通讯中的图片发送等任何在App中设计图片的 ...

最新文章

  1. [BZOJ4557][JLOI2016]侦查守卫
  2. WEEX 报错 TypeError: Converting circular structor to JSON 的解决方法
  3. “约见”面试官系列之常见面试题之第五十篇之title和alt的区别(建议收藏)
  4. 作者:褚金翔(1979-),男,中国农业科学院农业环境与可持续发展研究所助理研究员。...
  5. Spring Boot文档阅读笔记-@SpringBootApplication官方解析与实例(1.5.19)
  6. 判断 小程序_怎么判断小程序开发公司靠不靠谱?
  7. 盛京剑客系列17:市场暴跌下投资组合的调整
  8. 93、App Links (应用程序链接)实例
  9. javascript中常用的对象创建方式有哪些?
  10. jsp购物车(session版)
  11. mysql更新记录_如何查看 mysql 表中最近更新的记录
  12. 随机森林python反欺诈_基于三明治结构深度学习框架的金融反欺诈模型研究与应用...
  13. java FTPSClient 上传下载带证书的ftps服务器
  14. 利用百度api接口制作在线语音合成软件
  15. 谈一下为什么程序员不要进外包吧
  16. idea 修改项目名称的方法
  17. Asp连接数据库时的问题Microsoft OLE DB Provider for ODBC Drivers error ‘80004005‘
  18. 胸怀——勇气——智慧
  19. [论文阅读]PAN++: Towards Efficient and Accurate End-to-End Spotting of Arbitrarily-Shaped Text
  20. S7-1200数据类型

热门文章

  1. Android4.0与2.3的差异
  2. zynq 文件系统中加载PL fpga.bit笔记
  3. 很简单的自定义友好链接实现 .net core 2
  4. cin,getline用法和不同
  5. HDU 4609 3-idiots
  6. 二进制日志和数据更新的关系
  7. c++中构造函数 、析构函数的作用域详解
  8. js GPS 百度地图坐标转换
  9. android 从零单排 第一期 按键显示helloworld
  10. mount挂载windows共享文件夹