如何连接Android应用程序和Web服务?

问题描述:

如何连接Android应用和网络服务







公共类HttpTransportSE_Mnl扩展运输{



私人服务连接服务连接;



/ **

*创建设置url的HttpTransportSE实例

*

* @param url

* POST SOAP数据的目的地

* /

public HttpTransportSE_Mnl(String url){

super(null,url);

}



/ **

*使用set url创建HttpTransportSE的实例,并定义用于访问它的

*代理服务器

*

* @param proxy

*代理信息或 null 直接访问

* @param url

* POST SOAP数据的目的地

* /

public H ttpTransportSE_Mnl(代理代理,字符串网址){

super(代理,网址);

}



/ **

*用set url创建HttpTransportSE的实例

*

* @param url

*目的地发布SOAP数据

* @param timeout

*连接超时和读取超时(毫秒)

* /

public HttpTransportSE_Mnl(String url,int timeout){

super(url,timeout);

}



public HttpTransportSE_Mnl(Proxy proxy,String url,int timeout){

super(proxy,url,timeout);

}



/ **

*用set url创建HttpTransportSE实例

*

* @param url

* POST SOAP数据的目的地

* @param timeout

*连接超时和读取超时(毫秒)

* @param contentLength

*内容长度以字节为单位(如果事先知道)

* /

public HttpTransportSE_Mnl(String url,int timeout,int contentLength){

super(url,timeout);

}



public HttpTransportSE_Mnl(Proxy proxy,String url,int timeout,int contentLength){

super(proxy,url,timeout);

}



/ **

*设置所需的soapAction标题字段

*
* @param soapAction

*所需的soapAction

* @param信封

*包含信息的信封肥皂电话。

* @throws IOException

* @throws XmlPullParserException

* /

public void call(字符串oapAction,SoapEnvelope envelope)抛出IOException,XmlPullParserException {



调用(soapAction,envelope,null);

}



公共列表调用(String soapAction,SoapEnvelope信封,列表头)

抛出IOException,XmlPullParserException {

//返回调用(soapAction) ,信封,标题,null);

返回标题;

}



/ **

*使用给定的命名空间和给定的信封执行soap调用,提供

*用户需要的任何额外标头,例如cookie。由Web服务返回的标题将以

* 列表的形式返回给调用者> HeaderProperty 实例。

*

* @param soapAction

*命名空间用来执行通话。

* @param信封

*包含通话信息的信封。

* @param标题

* 列出 HeaderProperty 与SOAP请求一起发送的标题。

* @param outputFile

*用于将响应流式传输而不是解析它的文件,当文件不为空时发生流式传输

*

* @return Web服务返回的标题为列表

* HeaderProperty 实例。

* @throws例外

* /

pu blic String call(String soapAction,SoapEnvelope envelope,List headers,File outputFile,int intSegId,boolean isFileWrite)

throws Exception {

String strOutput = null;

尝试

{

if(soapAction == null){

soapAction =\\;
}



byte [] requestData = createRequestData(信封,UTF-8);



requestDump = debug? new String(requestData):null;

responseDump = null;



ServiceConnection connection = getServiceConnection();



connection.setRequestProperty(User-Agent,USER_AGENT);

// SOAPAction不是VER12的有效标头所以不要添加

// it

// @seehttp://code.google.com/p/ksoap2-android/issues/detail?id=67

if (envelope.version!= SoapSerializationEnvelope.VER12){

connection.setRequestProperty(SOAPAction,soapAction);

}



if(envelope.version == SoapSerializationEnvelope.VER12){

connection.setRequestProperty(Content-Type,CONTENT_TYPE_SOAP_XML_CHARSET_UTF_8);

} else {

connection.setRequestProperty(Content-Type,CONTENT_TYPE_XML_CHARSET_UTF_8);

}



connection.setRequestProperty(Connection,close);

connection.setRequestProperty(Accept-Encoding,gzip );

connection.setRequestProperty(Content-Length,+ requestData.length);

connection.setFixedLengthStreamingMode(requestData.length);



//传递用户提供的标题以及电话

if(headers!= null){

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

HeaderProperty hp =(HeaderProperty)headers.get(i);

connection.setRequestProperty(hp.getKey(),hp.getValue());
}

}



connection.setRequestMethod(POST);





OutputStream os = connection.openOutputStream();



os.write(requestData,0,requestData .length);

os.flush();

os.close();

requestData = null;

InputStream是;

列表retHeaders = null;

byte [] buf = null; //允许在使用后释放资源

int contentLength = 8192; //确定响应的大小并调整缓冲区大小

boolean gZippedContent = false;



//试试{

retHeaders = connection.getResponseProperties();

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

HeaderProperty hp = (HeaderProperty)retHeaders.get(i);

// HTTP响应代码有空键

if(null == hp.getKey()){

继续;

}

//如果我们知道响应的大小,我们应该使用这个大小来启动变量

if(hp.getKey()。equalsIgnoreCase(content-length)){

if(hp.getValue()!= null){

try {

contentLength = Integer.parseInt(hp.getValue());

} catch(NumberFormatException nfe){

contentLength = 8192;

}

}

}



//忽略大小写,因为用户发现在某些服务器上使用了所有小盒子

//即使根据规格它是错误的,我们宁愿让它工作..



if(hp.getKey()。equalsIgnoreCase(Content-Encoding)

&& hp.getValue()。equalsIgnoreCase(gzip)){

gZippedContent = true;

break;

}



}



if(gZippedContent){

is = getUnZippedInputStream(

new BufferedInputStream(connection.openInputStream(),contentLength));

} else {

is = new BufferedInputStream(connection.openInputStream(),contentLength);
}



System.gc();



if(isFileWrite){

strOutput =CashDldLog+ intSegId +。txt;

文件fileExits = new File(Environment.getExternalStorageDirectory()+/+ strOutput);



if(fileExits.exists())

fileExits.delete();



if(debug){

FileOutputStream bos = new FileOutputStream(

Environment.getExternalStorageDirectory()+/ CashDldLog+ intSegId +。txt);



byte [] bufnew = new byte [256];

while(true){

int rd = is.read(bufnew,0,256);



如果(rd == -1){

休息;

}



bos.write(bufnew,0,rd);

}

bos.flush();

bos.close();

is.close() ;

}

}否则{



parseResponse(信封,是);

SoapPrimitive readString =(SoapPrimitive)((SoapSerializationEnvelope)envelope).getResponse();

if(readString!= null)

strOutput = readString.toString();



is.close();

}

//释放所有资源

//输入流将在parseResponse中释放

os = null;

buf = null;

返回strOutput;

}

catch(Exception ex)

{

throw ex;

}



}



private InputStream getUnZippedInputStream(InputStream inputStream)throws IOException {

/ * Android 2.3的解决方法

(见http://*.com/questions/5131016/)

* /

尝试{

return(GZIPInputStream)inputStream;

} catch(ClassCastException e){

返回新的GZIPInputStream( inputStream);

}

}



public ServiceConnection getServiceConnection()抛出IOException {

if(serviceConnection == null){

serviceConnection = new ServiceConnectionSE(url,100000);

}

返回serviceConnection;
}



public String getHost(){



String retVal = null ;



尝试{

retVal =新网址(网址).getHost();

} catch(MalformedURLException e){

e.printStackTrace() ;

}



返回retVal;

}



public int getPort(){



int retVal = -1;



try {

retVal =新网址(网址).getPort();

} catch(MalformedURLException e){

e.printStackTrace();
}



返回retVal;

}



public String getPath(){



String retVal = null;



try {

retVal =新网址(网址).getPath();

} catch(MalformedURLException e){

e.printSt ackTrace();

}



返回retVal;

}

}

how can I connect the android app and web service



public class HttpTransportSE_Mnl extends Transport {

private ServiceConnection serviceConnection;

/**
* Creates instance of HttpTransportSE with set url
*
* @param url
* the destination to POST SOAP data
*/
public HttpTransportSE_Mnl(String url) {
super(null, url);
}

/**
* Creates instance of HttpTransportSE with set url and defines a
* proxy server to use to access it
*
* @param proxy
* Proxy information or null for direct access
* @param url
* The destination to POST SOAP data
*/
public HttpTransportSE_Mnl(Proxy proxy, String url) {
super(proxy, url);
}

/**
* Creates instance of HttpTransportSE with set url
*
* @param url
* the destination to POST SOAP data
* @param timeout
* timeout for connection and Read Timeouts (milliseconds)
*/
public HttpTransportSE_Mnl(String url, int timeout) {
super(url, timeout);
}

public HttpTransportSE_Mnl(Proxy proxy, String url, int timeout) {
super(proxy, url, timeout);
}

/**
* Creates instance of HttpTransportSE with set url
*
* @param url
* the destination to POST SOAP data
* @param timeout
* timeout for connection and Read Timeouts (milliseconds)
* @param contentLength
* Content Lenght in bytes if known in advance
*/
public HttpTransportSE_Mnl(String url, int timeout, int contentLength) {
super(url, timeout);
}

public HttpTransportSE_Mnl(Proxy proxy, String url, int timeout, int contentLength) {
super(proxy, url, timeout);
}

/**
* set the desired soapAction header field
*
* @param soapAction
* the desired soapAction
* @param envelope
* the envelope containing the information for the soap call.
* @throws IOException
* @throws XmlPullParserException
*/
public void call(String soapAction, SoapEnvelope envelope) throws IOException, XmlPullParserException {

call(soapAction, envelope, null);
}

public List call(String soapAction, SoapEnvelope envelope, List headers)
throws IOException, XmlPullParserException {
//return call(soapAction, envelope, headers, null);
return headers;
}

/**
* Perform a soap call with a given namespace and the given envelope providing
* any extra headers that the user requires such as cookies. Headers that are
* returned by the web service will be returned to the caller in the form of a
* List of HeaderProperty instances.
*
* @param soapAction
* the namespace with which to perform the call in.
* @param envelope
* the envelope the contains the information for the call.
* @param headers
* List of HeaderProperty headers to send with the SOAP request.
* @param outputFile
* a file to stream the response into rather than parsing it, streaming happens when file is not null
*
* @return Headers returned by the web service as a List of
* HeaderProperty instances.
* @throws Exception
*/
public String call(String soapAction, SoapEnvelope envelope, List headers, File outputFile,int intSegId,boolean isFileWrite)
throws Exception {
String strOutput=null;
try
{
if (soapAction == null) {
soapAction = "\"\"";
}

byte[] requestData = createRequestData(envelope, "UTF-8");

requestDump = debug ? new String(requestData) : null;
responseDump = null;

ServiceConnection connection = getServiceConnection();

connection.setRequestProperty("User-Agent", USER_AGENT);
// SOAPAction is not a valid header for VER12 so do not add
// it
// @see "http://code.google.com/p/ksoap2-android/issues/detail?id=67
if (envelope.version != SoapSerializationEnvelope.VER12) {
connection.setRequestProperty("SOAPAction", soapAction);
}

if (envelope.version == SoapSerializationEnvelope.VER12) {
connection.setRequestProperty("Content-Type", CONTENT_TYPE_SOAP_XML_CHARSET_UTF_8);
} else {
connection.setRequestProperty("Content-Type", CONTENT_TYPE_XML_CHARSET_UTF_8);
}

connection.setRequestProperty("Connection", "close");
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.setRequestProperty("Content-Length", "" + requestData.length);
connection.setFixedLengthStreamingMode(requestData.length);

// Pass the headers provided by the user along with the call
if (headers != null) {
for (int i = 0; i < headers.size(); i++) {
HeaderProperty hp = (HeaderProperty) headers.get(i);
connection.setRequestProperty(hp.getKey(), hp.getValue());
}
}

connection.setRequestMethod("POST");


OutputStream os = connection.openOutputStream();

os.write(requestData, 0, requestData.length);
os.flush();
os.close();
requestData = null;
InputStream is;
List retHeaders = null;
byte[] buf = null; // To allow releasing the resource after used
int contentLength = 8192; // To determine the size of the response and adjust buffer size
boolean gZippedContent = false;

// try {
retHeaders = connection.getResponseProperties();
for (int i = 0; i < retHeaders.size(); i++) {
HeaderProperty hp = (HeaderProperty)retHeaders.get(i);
// HTTP response code has null key
if (null == hp.getKey()) {
continue;
}
// If we know the size of the response, we should use the size to initiate vars
if (hp.getKey().equalsIgnoreCase("content-length") ) {
if ( hp.getValue() != null ) {
try {
contentLength = Integer.parseInt( hp.getValue() );
} catch ( NumberFormatException nfe ) {
contentLength = 8192;
}
}
}

// ignoring case since users found that all smaller case is used on some server
// and even if it is wrong according to spec, we rather have it work..

if (hp.getKey().equalsIgnoreCase("Content-Encoding")
&& hp.getValue().equalsIgnoreCase("gzip")) {
gZippedContent = true;
break;
}

}

if (gZippedContent) {
is = getUnZippedInputStream(
new BufferedInputStream(connection.openInputStream(),contentLength));
} else {
is = new BufferedInputStream(connection.openInputStream(),contentLength);
}

System.gc();

if(isFileWrite){
strOutput="CashDldLog" + intSegId + ".txt";
File fileExits = new File(Environment.getExternalStorageDirectory()+"/" + strOutput);

if(fileExits.exists())
fileExits.delete();

if (debug) {
FileOutputStream bos = new FileOutputStream(
Environment.getExternalStorageDirectory()+"/CashDldLog" + intSegId + ".txt");

byte[] bufnew = new byte[256];
while (true) {
int rd = is.read(bufnew, 0, 256);

if (rd == -1) {
break;
}

bos.write(bufnew, 0, rd);
}
bos.flush();
bos.close();
is.close();
}
}else{

parseResponse(envelope, is);
SoapPrimitive readString = (SoapPrimitive)((SoapSerializationEnvelope) envelope).getResponse();
if(readString!=null)
strOutput = readString.toString();

is.close();
}
// release all resources
// input stream is will be released inside parseResponse
os = null;
buf = null;
return strOutput;
}
catch(Exception ex)
{
throw ex;
}

}

private InputStream getUnZippedInputStream(InputStream inputStream) throws IOException {
/* workaround for Android 2.3
(see http://*.com/questions/5131016/)
*/
try {
return (GZIPInputStream) inputStream;
} catch (ClassCastException e) {
return new GZIPInputStream(inputStream);
}
}

public ServiceConnection getServiceConnection() throws IOException {
if (serviceConnection == null) {
serviceConnection = new ServiceConnectionSE(url, 100000);
}
return serviceConnection;
}

public String getHost() {

String retVal = null;

try {
retVal = new URL(url).getHost();
} catch (MalformedURLException e) {
e.printStackTrace();
}

return retVal;
}

public int getPort() {

int retVal = -1;

try {
retVal = new URL(url).getPort();
} catch (MalformedURLException e) {
e.printStackTrace();
}

return retVal;
}

public String getPath() {

String retVal = null;

try {
retVal = new URL(url).getPath();
} catch (MalformedURLException e) {
e.printStackTrace();
}

return retVal;
}
}