안 드 로 이 드 학습 13---인터넷 통신(3)웹 서비스 와 통신
12215 단어 androidwebservicexfire네트워크 통신
package com.iflytek.services;
public interface IFileServices {
/**
*
*
* @param fileName
*
* @param content
*
* @throws Exception
*/
public void save(String fileName, String content) throws Exception;
/**
*
*
* @param fileName
*
* @return
* @throws Exception
*/
public String load(String fileName) throws Exception;
}
클래스 FileServicesImpl.java 구현
package com.iflytek.services.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner;
import com.iflytek.services.IFileServices;
public class FileServicesImpl implements IFileServices {
public String load(String fileName) throws Exception {
File file = new File("D:" + File.separator + "xdwang" + File.separator
+ fileName);
if (!file.exists()) { //
return null;
}
StringBuffer buf = new StringBuffer();
Scanner scan = new Scanner(new FileInputStream(file));
scan.useDelimiter("
");
while (scan.hasNext()) {
buf.append(scan.next());
}
scan.close();
return buf.toString();
}
public void save(String fileName, String content) throws Exception {
File file = new File("D:" + File.separator + "xdwang" + File.separator
+ fileName);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
PrintStream out = new PrintStream(new FileOutputStream(file));
out.print(content);
out.close();
}
}
services.xml 설정
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xfire.codehaus.org/config/1.0">
<service>
<name>iflytek</name>
<serviceClass>
com.iflytek.services.IFileServices
</serviceClass>
<implementationClass>
com.iflytek.services.impl.FileServicesImpl
</implementationClass>
<style>wrapped</style>
<use>literal</use>
<scope>application</scope>
</service>
</beans>
이 때 브 라 우 저 에 입력:
http://IP:8080/AndroidWebServiceProject/services/iflytek?wsdl열 수 있 습 니 다.이 를 위해 웹 서비스 프로그램의 서버 엔 드 가 개발 되 었 습 니 다.다음은 안 드 로 이 드 클 라 이언 트 프로그램의 개발 을 진행 하 겠 습 니 다.
Android 프로그램 은 웹 서비스 프로그램 을 호출 하려 고 합 니 다.JSP/servlet 또는 Socket 프로그램 을 호출 하 는 것 처럼 시스템 이 제공 하 는 클래스 를 직접 사용 하지 않 습 니 다.Android 에 서 는 웹 서비스 와 직접 호출 하 는 조작 라 이브 러 리 를 제공 하지 않 기 때문에 제3자 가 제공 하 는 라 이브 러 리 에 의존 해 야 완성 할 수 있 습 니 다.비교적 자주 사용 하 는 것 은 ksoap 라 이브 러 리 입 니 다.http://code.google.com/p/ksoap2-android/에서 다운로드 할 수 있다.
다운로드 후 Android 프로젝트 의 Java Build Path 에 설정 하면 됩 니 다.설정 이 완료 되면 Android 에서 프로그램 을 작성 하여 WebService 프로그램 을 호출 할 수 있 습 니 다.구체 적 인 절 차 는 다음 과 같 습 니 다.
1.org.ksoap 2.serialization.SoapObject 류 를 통 해 호출 할 WebService 프로그램 에 필요 한 이름 컨트롤 을 지정 합 니 다.SoapObject 류 의 일반적인 방법 은 다음 과 같 습 니 다.
No.
방법.
묘사 하 다.
1
Public SoapObject(String namespace,String name)
실례 화 SoapObject 클래스 대상
2
Public String getName()
호출 할 방법 이름 가 져 오기
3
Public String getNameSpace()
Soap 대상 의 네 임 스페이스 가 져 오기
4
Public Object getProperty(java.lang.String name)
지정 한 이름 의 속성 가 져 오기
5
Public SoapObject addProperty(String name,Object value)
WebService 호출 방법 을 설정 할 때 필요 한 인자
2.SoapObject 의 실례 화 대상 을 얻 은 후 SoapObject 류 의 addProperty()방법 을 통 해 save()방법 을 호출 할 때 필요 한 인 자 를 설정 할 수 있 습 니 다.설정 순 서 는 웹 서비스 프로그램의 save()방법의 매개 변수 순서 와 일치 해 야 합 니 다.addProperty()방법 을 호출 할 때 반드시 서버 측의 방법 이름,매개 변수 이름 과 같 지 않 아야 합 니 다.프로그램 이 실 행 될 때 도 이름 에 따라 매개 변 수 를 설정 하 는 순서에 따라 결정 되 기 때문이다.
3.WebService 프로그램 을 호출 하 는 SOAP 요청 정 보 를 생 성 합 니 다.이 때 org.ksoap 2.serialization.SoapSerializationEnvelope 류 를 이용 하여 완성 할 수 있 습 니 다.이러한 일반적인 방법 은 다음 과 같 습 니 다.
No.
방법,상수,속성
유형
묘사 하 다.
1
Public static final int VER11
상수
SOAP 11 버 전 사용
2
Public Object bodyIn
속성
입력 한 SoapObject 대상 봉인
3
Public Object bodyOut
속성
출력 을 봉인 하 는 SoapObject 대상
4
Public Boolean dotNet
속성
.NET 연결 여 부 를 false 로 설정 합 니 다.true 로 설정 하면 서버 에서 요청 인 자 를 받 아들 일 수 없습니다.
5
Public SoapSerializationEnvelope(int version)
구조
실례 화 SoapSerializationEnvelope 클래스 대상
6
Public void setOutputSoapObject(Object soapObject)
수수 하 다
출력 할 SoapObject 대상 설정
4.org.ksoap 2.transport.HttpTransportSE 클래스 대상 을 만 들 고 이 대상 을 이용 하여 WebService 단 을 호출 하 는 작업 방법 은 다음 과 같 습 니 다.
No.
방법,속성
묘사 하 다.
1
Public Boolean debug
디 버 깅 할 지 여부 입 니 다.true 로 설정 하면 디 버 깅 을 표시 합 니 다.
2
Public HttpTransportSE(String url)
Http TransportSE 클래스 의 대상 을 예화 합 니 다.
3
public void call(String soapAction, SoapEnvelope envelope) throws IOException, XmlPullParserException
웹 서비스 단 을 호출 하 는 방법
5.WebService 의 반환 값 수락
Android 클 라 이언 트 코드
WebServiceActivity.java
package com.iflytek.demo;
import java.io.IOException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class WebServiceActivity extends Activity {
private Button saveBtn = null;
private Button loadBtn = null;
private TextView showTxt = null;
/**
* WebService
*/
private static final String NAMESPACE = "http://IP/";
/**
* , *.wsdl
*/
private static String URL = "http://IP:8080/AndroidWebServiceProject/services/iflytek";
/**
*
*/
private static final String SAVE_METHOD_NAME = "save";
/**
*
*/
private static final String LOAD_METHOD_NAME = "load";
private static String SOAP_ACTION = "http://IP:8080/AndroidWebServiceProject/services/";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.saveBtn = (Button) super.findViewById(R.id.save);
this.loadBtn = (Button) super.findViewById(R.id.load);
this.showTxt = (TextView) super.findViewById(R.id.show);
this.saveBtn.setOnClickListener(new SaveOnClickListenerImpl());
this.loadBtn.setOnClickListener(new LoadOnClickListenerImpl());
}
private class SaveOnClickListenerImpl implements OnClickListener {
@Override
public void onClick(View v) {
final AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
@Override
protected void onPostExecute(String result) {
Toast.makeText(WebServiceActivity.this, " ",
Toast.LENGTH_SHORT).show();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(Void... arg0) {
SoapObject soapObject = new SoapObject(NAMESPACE,
SAVE_METHOD_NAME);
soapObject.addProperty("fileName", "xdwang.txt");//
soapObject.addProperty("content", "Hello, xdwang ");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);//
envelope.bodyOut = soapObject;//
envelope.dotNet = false;// .NET
envelope.setOutputSoapObject(soapObject);// SoapObjet
HttpTransportSE trans = new HttpTransportSE(URL);//
trans.debug = true; //
try {
trans.call(SOAP_ACTION, envelope);//
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
return null;
}
};
task.execute();
}
}
private class LoadOnClickListenerImpl implements OnClickListener {
@Override
public void onClick(View v) {
final AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
@Override
protected void onPostExecute(String result) {
WebServiceActivity.this.showTxt
.setText("Web Service :" + result);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(Void... arg0) {
SoapObject soapObject = new SoapObject(NAMESPACE,
LOAD_METHOD_NAME);
soapObject.addProperty("fileName", "xdwang.txt");//
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);//
envelope.bodyOut = soapObject;//
envelope.dotNet = false;// .NET
envelope.setOutputSoapObject(soapObject);// SoapObjet
HttpTransportSE trans = new HttpTransportSE(URL);//
trans.debug = true; //
try {
trans.call(SOAP_ACTION, envelope);//
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
SoapObject result = (SoapObject) envelope.bodyIn;//
return result.getProperty(0).toString();
}
};
task.execute();
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/save"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" WebService " />
<Button
android:id="@+id/load"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" WebService " />
<TextView
android:id="@+id/show"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" " />
</LinearLayout>
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Kotlin의 기초 - 2부지난 글에서는 Kotlin이 무엇인지, Kotlin의 특징, Kotlin에서 변수 및 데이터 유형을 선언하는 방법과 같은 Kotlin의 기본 개념에 대해 배웠습니다. 유형 변환은 데이터 변수의 한 유형을 다른 데이터...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.