android webservice 后台服务,Android 调用 Webservice的实现过程

之前帮朋友做了一个服务端是Webservice的项目,把实现过程中的一下流程简单记录一下

1、开启Webservice服务

一般后台会开启一个服务给你或者为了直接方便调试的话,也可以自己用androidStudio 打开这个Webservice项目,如下图所示:

0fb8b6319bea?tdsourcetag=s_pcqq_aiomsg

image.png

0fb8b6319bea?tdsourcetag=s_pcqq_aiomsg

image.png

0fb8b6319bea?tdsourcetag=s_pcqq_aiomsg

image.png

2、打开wsdl查看接口信息

0fb8b6319bea?tdsourcetag=s_pcqq_aiomsg

image.png

0fb8b6319bea?tdsourcetag=s_pcqq_aiomsg

image.png

0fb8b6319bea?tdsourcetag=s_pcqq_aiomsg

image.png

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

基本入参都String,因为之前跟后台联调的时候发现传对象一直没成功,就折中改为传jsonObject的方式,后台再去转为对象

3、WebServiceHttpUtils 封装

/**

* WebService android端调用

* Created by Administrator on 2018/7/21.

*/

public class WebServiceHttpUtils {

private static final String TAG = WebServiceHttpUtils.class.getSimpleName();

/**

* 调用webservice接口获取 SoapObject 对象

* @param serviceNameSpace webservice的命名空间

* @param serviceUrl webservice的请求地址 要带?wsdl

* @param mathodName 调用webservice的函数名

* @param isHasParameters 是否带参

* @param parameters 参数集合,Map

* @return SoapObject 对象

* @throws IOException

* @throws XmlPullParserException

*/

public static String call(String serviceNameSpace, String serviceUrl,

String mathodName, boolean isHasParameters,

Map parameters) {

//要调用的方法名称

SoapObject request = new SoapObject(serviceNameSpace, mathodName);

//带参

LogUtil.d(TAG,"isHasParameters========"+isHasParameters);

if (isHasParameters) {

if (parameters != null) {

LogUtil.d(TAG,"parameters != null========");

for (Map.Entry entry : parameters.entrySet()) {

String key = entry.getKey();

Object value = entry.getValue();

LogUtil.d(TAG,"key========"+key);

LogUtil.d(TAG,"value======="+value);

if (!TextUtils.isEmpty(key) && value != null) {

// 设置参数

// 当这里的参数设置为arg0、arg1、arg2……argn的时候竟然是正确的。

request.addProperty(key, value);

}

}

}else {

LogUtil.d(TAG,"parameters == null========");

}

}else {

}

//创建SoapSerializationEnvelope 对象,同时指定soap版本号(之前在wsdl中看到的)

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11);

envelope.bodyOut = request;//由于是发送请求,所以是设置bodyOut

// envelope.dotNet = true;//由于是.net开发的webservice,所以这里要设置为true

HttpTransportSE httpTransportSE = new HttpTransportSE(serviceUrl);

try {

httpTransportSE.call(null, envelope);//调用

// 获取返回的数据

SoapObject soapObject = (SoapObject) envelope.bodyIn;

String respoend = soapObject.getProperty(0).toString();

Log.d(TAG,"接口-"+mathodName+"-请求结果:"+respoend);

return respoend;

} catch (IOException e) {

e.printStackTrace();

} catch (XmlPullParserException e) {

e.printStackTrace();

}

return "";

}

}

4、BaseApplication封装

/**

*

* Created by psl on 2017/5/7.

*/

public class BaseApplication extends MultiDexApplication {

public static Context context;

private static RetrofitAPIImpl mRetrofitAPI;

private static Retrofit mRetrofit;

private static BaseApplication sInstence;

// 命名空间

public static final String nameSpace = "http://service.linkfair.com/";

// serviceUrl

public static final String serviceUrl = "http://192.168.4.221:80/8888/linkfair?wsdl";

public static BaseApplication getInstence() {

return sInstence;

}

@Override

public void onCreate() {

super.onCreate();

sInstence = this;

context = this;

}

}

5、无参调用方式

showLoading();

//仓库 启动后台异步线程进行连接webService操作,并且根据返回结果在主线程中改变UI

QueryListWarehouseTask queryListWarehouseTask = new QueryListWarehouseTask();

//启动后台任务

queryListWarehouseTask.execute();

/**

* 选择仓库

*/

class QueryListWarehouseTask extends AsyncTask {

@Override

protected String doInBackground(Void... voids) {

String result = WebServiceHttpUtils.call(BaseApplication.getInstence().nameSpace,BaseApplication.getInstence().serviceUrl,LISTWAREHOUSE_METHODNAME,false,null);

LogUtil.d(TAG,"result========"+result);

return result;

}

@Override

//此方法可以在主线程改变UI

protected void onPostExecute(String result) {

dismissLoading();

// 将WebService返回的结果显示在TextView中

Log.d(TAG,"onPostExecute============result==============="+result);

if (!TextUtils.isEmpty(result)){

Gson gson = new Gson();

List wareHouseBeanList = gson.fromJson(result,new TypeToken>(){}.getType());

if (wareHouseBeanList != null && wareHouseBeanList.size() > 0){

mTestSelectArr = new String[wareHouseBeanList.size()];

for (int i = 0; i < wareHouseBeanList.size(); i++) {

WareHouseBean wareHouseBean = wareHouseBeanList.get(i);

mTestSelectArr[i] = wareHouseBean.getName();

mWareHouseList.add(wareHouseBean);

}

}else {

}

}

}

}

6、有参调用方式

showLoading();

//启动后台异步线程进行连接webService操作,并且根据返回结果在主线程中改变UI

QueryCcanMaterialTask queryyCcanMaterialTask = new QueryCcanMaterialTask();

//启动后台任务

queryyCcanMaterialTask.execute("123456");

/**

* 扫码得到物料

*/

class QueryCcanMaterialTask extends AsyncTask {

@Override

protected String doInBackground(String... params) {

Map map = new HashMap<>();

map.put("arg0",params[0]);

String result = WebServiceHttpUtils.call(BaseApplication.getInstence().nameSpace,BaseApplication.getInstence().serviceUrl,SCANMATERIAL_METHODNAME,true,map);

LogUtil.d(TAG,"result========"+result);

return result;

}

@Override

//此方法可以在主线程改变UI

protected void onPostExecute(String result) {

dismissLoading();

// 将WebService返回的结果显示在TextView中

Log.d(TAG,"onPostExecute============result==============="+result);

if (!TextUtils.isEmpty(result)){

Gson gson = new Gson();

ScanMaterialBean scanMaterialBean = gson.fromJson(result,ScanMaterialBean.class);

if (scanMaterialBean != null){

if (scanMaterialBean.isSuccess()){

if (scanMaterialBean.getContent() != null){

list.add(scanMaterialBean.getContent());

adapter.notifyDataSetChanged();

rvList.scrollToPosition(list.size()-1);

}

}else {

}

}else {

ToastUtil.toast(context,"查询数据为空!");

}

}

}

}

7、把入参List改为JsonArray的调用方式

/**

* 处理提交数据

*/

private void delComfirmData(){

//提交材料 下面是提交类子

// 真实使用请按照下面的格式遍历列表adapter的列表中的数据(ArrayList list)

//就是把遍历(ArrayList list) 添加到

List InWarehouseList = new ArrayList<>();

if (list != null && list.size() > 0){

for (int i = 0; i < list.size(); i++) {

ScanMaterialBean.ContentBean contentBean = list.get(i);

InWarehouse mInWarehouse = new InWarehouse();

mInWarehouse.id = mWareHouseId;

mInWarehouse.materialId = contentBean.getId();

mInWarehouse.taskCount = 1; //假数据 需要根据项目填真实数据

mInWarehouse.putCount = 1; //假数据 需要根据项目填真实数据

mInWarehouse.name = contentBean.getName();

mInWarehouse.model =contentBean.getModel();

InWarehouseList.add(mInWarehouse);

}

JSONArray jsonArray = new JSONArray();

JSONObject jsonObject = new JSONObject();

JSONObject tmpObj = null;

int count = InWarehouseList.size();

for(int i = 0; i < count; i++)

{

InWarehouse inWarehouse = InWarehouseList.get(i);

tmpObj = new JSONObject();

try {

tmpObj.put("id" ,inWarehouse.id);

tmpObj.put("materialId",inWarehouse.id);

tmpObj.put("taskCount", inWarehouse.id);

tmpObj.put("putCount" ,inWarehouse.id);

tmpObj.put("name", inWarehouse.id);

tmpObj.put("model",inWarehouse.id);

} catch (JSONException e) {

e.printStackTrace();

}

jsonArray.put(tmpObj);

tmpObj = null;

}

String personInfos = jsonArray.toString(); // 将JSONArray转换得到String

showLoading();

//启动后台异步线程进行连接webService操作,并且根据返回结果在主线程中改变UI

QueryInsertInhouseTask queryListWarehouseTask = new QueryInsertInhouseTask();

//启动后台任务

queryListWarehouseTask.execute(personInfos);

}

}

/**

* 仓库录入

*/

class QueryInsertInhouseTask extends AsyncTask {

@Override

protected String doInBackground(String... strings) {

Map map = new HashMap<>();

map.put("arg0",strings[0]);

String result = WebServiceHttpUtils.call(BaseApplication.getInstence().nameSpace,BaseApplication.getInstence().serviceUrl,INSERTINHOUSE_METHODNAME,true,map);

LogUtil.d(TAG,"result========"+result);

return result;

}

@Override

//此方法可以在主线程改变UI

protected void onPostExecute(String result) {

dismissLoading();

// 将WebService返回的结果显示在TextView中

Log.d(TAG,"onPostExecute============result==============="+result);

Gson gson = new Gson();

InsertInhouseBean mInsertInhouseBean = gson.fromJson(result,InsertInhouseBean.class);

if (mInsertInhouseBean != null){

ToastUtil.toast(context,!TextUtils.isEmpty(mInsertInhouseBean.message)?mInsertInhouseBean.message:"");

}else {

ToastUtil.toast(context,"查询数据为空!");

}

}

}

8、完整代码

/**

* 采购入库

*/

public class PurchaseAndStorageActivity extends BaseActivity {

private static final String TAG = PurchaseAndStorageActivity.class.getSimpleName();

private final static String SCAN_ACTION = ScanManager.ACTION_DECODE;//default action

private ActionBar actionBar;

@BindView(R.id.title_bar)

TitleLayout titleBar;

@BindView(R.id.tv_storage_title)

TextView tvStorageTitle;

@BindView(R.id.tv_storage)

TextView tvStorage;

@BindView(R.id.bn_select)

Button bnSelect;

@BindView(R.id.rv_list)

RecyclerView rvList;

@BindView(R.id.bn_comfirm)

Button bnComfirm;

@BindView(R.id.bn_cancel)

Button bnCancel;

@BindView(R.id.et_scan)

EditText etScan;

private Context mContext;

private Unbinder unbinder;

private SelectPopupWindow selectPopupWindow;

private Vibrator mVibrator;

private ScanManager mScanManager;

private SoundPool soundpool = null;

private int soundid;

private String barcodeStr;

private boolean isScaning = false;

private String[] mTestSelectArr = null;

private ArrayList mWareHouseList = new ArrayList<>();

// 查询仓库调用的方法名称

private static final String LISTWAREHOUSE_METHODNAME = "listWarehouse";

// 扫码得到物料调用的方法名称

private static final String SCANMATERIAL_METHODNAME = "scanMaterial";

// 仓库录入调用的方法名称

private static final String INSERTINHOUSE_METHODNAME = "insertInhouse";

private PurchaseAndStorageAdapter adapter;

private ArrayList list;

private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {

@Override

public void onReceive(Context context, Intent intent) {

// TODO Auto-generated method stub

isScaning = false;

soundpool.play(soundid, 1, 1, 0, 0, 1);

mVibrator.vibrate(100);

byte[] barcode = intent.getByteArrayExtra(ScanManager.DECODE_DATA_TAG);

int barcodelen = intent.getIntExtra(ScanManager.BARCODE_LENGTH_TAG, 0);

byte temp = intent.getByteExtra(ScanManager.BARCODE_TYPE_TAG, (byte) 0);

android.util.Log.i("debug", "----codetype--" + temp);

barcodeStr = new String(barcode, 0, barcodelen);

etScan.append(" length:" +barcodelen);

etScan.append(" barcode:" +barcodeStr);

etScan.setText(barcodeStr);

showLoading();

//启动后台异步线程进行连接webService操作,并且根据返回结果在主线程中改变UI

QueryCcanMaterialTask queryyCcanMaterialTask = new QueryCcanMaterialTask();

//启动后台任务

queryyCcanMaterialTask.execute("123456");

}

};

private int mWareHouseId;

@Override

public int setLayout() {

return R.layout.activity_purchase_and_storage;

}

@Override

public void initUI() {

mContext = this;

unbinder = ButterKnife.bind(this);

etScan.setFocusable(false);

mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

}

/**

* 初始化RecyclerView

*/

private void initRecyclerView() {

adapter = new PurchaseAndStorageAdapter(mContext,list);

LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(mContext);

rvList.setLayoutManager(mLinearLayoutManager);

rvList.setAdapter(adapter);

}

@Override

public void initData() {

list = new ArrayList<>();

mWareHouseList.clear();

initRecyclerView();

}

@Override

public void addListeners() {

bnSelect.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

if (mTestSelectArr == null || mTestSelectArr.length == 0){

ToastUtil.toast(context,"仓库数据为空!");

}else {

initSelect();

}

}

});

}

@Override

public void onClick(View v) {

super.onClick(v);

//数据提交按钮

if (v.equals(bnComfirm)){

delComfirmData();

}else if (v.equals(bnCancel)){

finish();

}

}

/**

* 处理提交数据

*/

private void delComfirmData(){

//提交材料 下面是提交类子

// 真实使用请按照下面的格式遍历列表adapter的列表中的数据(ArrayList list)

//就是把遍历(ArrayList list) 添加到

List InWarehouseList = new ArrayList<>();

if (list != null && list.size() > 0){

for (int i = 0; i < list.size(); i++) {

ScanMaterialBean.ContentBean contentBean = list.get(i);

InWarehouse mInWarehouse = new InWarehouse();

mInWarehouse.id = mWareHouseId;

mInWarehouse.materialId = contentBean.getId();

mInWarehouse.taskCount = 1; //假数据 需要根据项目填真实数据

mInWarehouse.putCount = 1; //假数据 需要根据项目填真实数据

mInWarehouse.name = contentBean.getName();

mInWarehouse.model =contentBean.getModel();

InWarehouseList.add(mInWarehouse);

}

JSONArray jsonArray = new JSONArray();

JSONObject jsonObject = new JSONObject();

JSONObject tmpObj = null;

int count = InWarehouseList.size();

for(int i = 0; i < count; i++)

{

InWarehouse inWarehouse = InWarehouseList.get(i);

tmpObj = new JSONObject();

try {

tmpObj.put("id" ,inWarehouse.id);

tmpObj.put("materialId",inWarehouse.id);

tmpObj.put("taskCount", inWarehouse.id);

tmpObj.put("putCount" ,inWarehouse.id);

tmpObj.put("name", inWarehouse.id);

tmpObj.put("model",inWarehouse.id);

} catch (JSONException e) {

e.printStackTrace();

}

jsonArray.put(tmpObj);

tmpObj = null;

}

String personInfos = jsonArray.toString(); // 将JSONArray转换得到String

showLoading();

//启动后台异步线程进行连接webService操作,并且根据返回结果在主线程中改变UI

QueryInsertInhouseTask queryListWarehouseTask = new QueryInsertInhouseTask();

//启动后台任务

queryListWarehouseTask.execute(personInfos);

}

}

private void initSelect() {

//实例化SelectPicPopupWindow

selectPopupWindow = new SelectPopupWindow(PurchaseAndStorageActivity.this, mTestSelectArr, new SelectPopupWindow.ItemClickPositionListener() {

@Override

public void getItemClickPosition(int position) {

tvStorage.setText(mTestSelectArr[position]);

WareHouseBean wareHouseBean = mWareHouseList.get(position);

mWareHouseId = wareHouseBean.getId();

}

});

//显示窗口

selectPopupWindow.showAtLocation(bnSelect, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置

}

private void initScan() {

// TODO Auto-generated method stub

mScanManager = new ScanManager();

mScanManager.openScanner();

mScanManager.switchOutputMode( 0);

soundpool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE

soundid = soundpool.load("/etc/Scan_new.ogg", 1);

}

@Override

protected void onResume() {

// TODO Auto-generated method stub

super.onResume();

initScan();

etScan.setText("");

IntentFilter filter = new IntentFilter();

int[] idbuf = new int[]{PropertyID.WEDGE_INTENT_ACTION_NAME, PropertyID.WEDGE_INTENT_DATA_STRING_TAG};

String[] value_buf = mScanManager.getParameterString(idbuf);

if(value_buf != null && value_buf[0] != null && !value_buf[0].equals("")) {

filter.addAction(value_buf[0]);

} else {

filter.addAction(SCAN_ACTION);

}

registerReceiver(mScanReceiver, filter);

showLoading();

//仓库 启动后台异步线程进行连接webService操作,并且根据返回结果在主线程中改变UI

QueryListWarehouseTask queryListWarehouseTask = new QueryListWarehouseTask();

//启动后台任务

queryListWarehouseTask.execute();

}

@Override

protected void onPause() {

// TODO Auto-generated method stub

super.onPause();

if(mScanManager != null) {

mScanManager.stopDecode();

isScaning = false;

}

unregisterReceiver(mScanReceiver);

}

@Override

protected void onDestroy() {

super.onDestroy();

if (unbinder != null) {

unbinder.unbind();

}

}

/**

* 选择仓库

*/

class QueryListWarehouseTask extends AsyncTask {

@Override

protected String doInBackground(Void... voids) {

String result = WebServiceHttpUtils.call(BaseApplication.getInstence().nameSpace,BaseApplication.getInstence().serviceUrl,LISTWAREHOUSE_METHODNAME,false,null);

LogUtil.d(TAG,"result========"+result);

return result;

}

@Override

//此方法可以在主线程改变UI

protected void onPostExecute(String result) {

dismissLoading();

// 将WebService返回的结果显示在TextView中

Log.d(TAG,"onPostExecute============result==============="+result);

if (!TextUtils.isEmpty(result)){

Gson gson = new Gson();

List wareHouseBeanList = gson.fromJson(result,new TypeToken>(){}.getType());

if (wareHouseBeanList != null && wareHouseBeanList.size() > 0){

mTestSelectArr = new String[wareHouseBeanList.size()];

for (int i = 0; i < wareHouseBeanList.size(); i++) {

WareHouseBean wareHouseBean = wareHouseBeanList.get(i);

mTestSelectArr[i] = wareHouseBean.getName();

mWareHouseList.add(wareHouseBean);

}

}else {

}

}

}

}

/**

* 扫码得到物料

*/

class QueryCcanMaterialTask extends AsyncTask {

@Override

protected String doInBackground(String... params) {

Map map = new HashMap<>();

map.put("arg0",params[0]);

String result = WebServiceHttpUtils.call(BaseApplication.getInstence().nameSpace,BaseApplication.getInstence().serviceUrl,SCANMATERIAL_METHODNAME,true,map);

LogUtil.d(TAG,"result========"+result);

return result;

}

@Override

//此方法可以在主线程改变UI

protected void onPostExecute(String result) {

dismissLoading();

// 将WebService返回的结果显示在TextView中

Log.d(TAG,"onPostExecute============result==============="+result);

if (!TextUtils.isEmpty(result)){

Gson gson = new Gson();

ScanMaterialBean scanMaterialBean = gson.fromJson(result,ScanMaterialBean.class);

if (scanMaterialBean != null){

if (scanMaterialBean.isSuccess()){

if (scanMaterialBean.getContent() != null){

list.add(scanMaterialBean.getContent());

adapter.notifyDataSetChanged();

rvList.scrollToPosition(list.size()-1);

}

}else {

}

}else {

ToastUtil.toast(context,"查询数据为空!");

}

}

}

}

/**

* 仓库录入

*/

class QueryInsertInhouseTask extends AsyncTask {

@Override

protected String doInBackground(String... strings) {

Map map = new HashMap<>();

map.put("arg0",strings[0]);

String result = WebServiceHttpUtils.call(BaseApplication.getInstence().nameSpace,BaseApplication.getInstence().serviceUrl,INSERTINHOUSE_METHODNAME,true,map);

LogUtil.d(TAG,"result========"+result);

return result;

}

@Override

//此方法可以在主线程改变UI

protected void onPostExecute(String result) {

dismissLoading();

// 将WebService返回的结果显示在TextView中

Log.d(TAG,"onPostExecute============result==============="+result);

Gson gson = new Gson();

InsertInhouseBean mInsertInhouseBean = gson.fromJson(result,InsertInhouseBean.class);

if (mInsertInhouseBean != null){

ToastUtil.toast(context,!TextUtils.isEmpty(mInsertInhouseBean.message)?mInsertInhouseBean.message:"");

}else {

ToastUtil.toast(context,"查询数据为空!");

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值