与web服务和android交互

时间:2011-09-29 18:51:59

标签: android web-services

我想向网络服务http://www.w3schools.com/webservices/tempconvert.asmx发出请求,但我无法得到正确的响应,而是收到了400条不良请求。

这是我的AsyncTask doInBackground

protected String doInBackground(Void... params) {
    String s=null;
    try {

        restclient client1 = new restclient("http://www.w3schools.com/webservices/tempconvert.asmx");
        client1.AddParam("Celsius", "12");

        client1.AddHeader("Content-Type", "text/xml; charset=utf-8" );
        client1.AddHeader("SOAPAction", "http://tempuri.org/CelsiusToFahrenheit");


            client1.Execute(RequestMethod.POST);
            s = client1.getResponse();
            return s;
            } catch (Exception e) {

                e.printStackTrace();
            }


    return  s;       
}

我有一个关于client1的课程,我从帖子中找到了(现在无法找到该链接)

public class restclient {

public enum RequestMethod {
    GET, POST
}

private ArrayList<NameValuePair> params;
private ArrayList<NameValuePair> headers;

private String url;

private int responseCode;
private String message;

private String response;

public String getResponse() {
    return response;
}

public String getErrorMessage() {
    return message;
}

public int getResponseCode() {
    return responseCode;
}

public restclient(String url) {
    this.url = url;
    params = new ArrayList<NameValuePair>();
    headers = new ArrayList<NameValuePair>();
}

public void AddParam(String name, String value) {
    params.add(new BasicNameValuePair(name, value));
}

public void AddHeader(String name, String value) {
    headers.add(new BasicNameValuePair(name, value));
}

public void Execute(RequestMethod method) throws Exception {
    switch (method) {
    case GET: {
        // add parameters
        String combinedParams = "";
        if (!params.isEmpty()) {
            combinedParams += "?";
            for (NameValuePair p : params) {
                String paramString = p.getName() + "="
                        + URLEncoder.encode(p.getValue(), "UTF-8");
                if (combinedParams.length() > 1) {
                    combinedParams += "&" + paramString;
                } else {
                    combinedParams += paramString;
                }
            }
        }

        HttpGet request = new HttpGet(url + combinedParams);

        // add headers
        for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
        }

        executeRequest(request, url);
        break;
    }
    case POST: {
        HttpPost request = new HttpPost(url);

        // add headers
        for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
        }

        if (!params.isEmpty()) {
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        }

        executeRequest(request, url);
        break;
    }
    }
}

private void executeRequest(HttpUriRequest request, String url) {
    HttpClient client = new DefaultHttpClient();

    HttpResponse httpResponse;

    try {
        httpResponse = client.execute(request);
        responseCode = httpResponse.getStatusLine().getStatusCode();
        message = httpResponse.getStatusLine().getReasonPhrase();

        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {

            InputStream instream = entity.getContent();
            response = convertStreamToString(instream);

            // Closing the input stream will trigger connection release
            instream.close();
        }

    } catch (ClientProtocolException e) {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
    } catch (IOException e) {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
    }
}

private static String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

}

我还包括访问互联网

 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.android.test"
  android:versionCode="1"
  android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />

<uses-permission android:name="android.permission.INTERNET" />


<application android:icon="@drawable/icon" android:label="@string/app_name">
   .....         
</application>

我尝试发帖时只收到错误的请求回复。我需要使用更多参数吗?我觉得身体错了,但我找不到解决办法。

2 个答案:

答案 0 :(得分:0)

您确定POST是正确的吗?当我在Chrome中为该网址执行GET时,我得到200 OK。也许您应该尝试更改以下内容?

client1.Execute(RequestMethod.GET);

答案 1 :(得分:0)

编辑:我刚看到你的内容类型标题,你试过“application / soap + xml”吗?此外,SOAP需要POST我相信,GET将无法正常工作,所以你是正确的POST。

EDIT2:您使用的客户端类无法运行。您需要在POST请求的主体中发送XML,并将其包装在SOAP XML包装器中。 XML需要遵循端点的WSDL结构。我建议使用SOAP UI(下面的链接)来确定XML应该是什么样子。如果你想获得想象力,你应该创建一个类序列化,使其看起来与SOAP UI创建的请求完全相同。

对于SOAP服务,您几乎总是可以通过将WSDL添加到端点url来访问WSDL: http://www.w3schools.com/webservices/tempconvert.asmx?wsdl

如果那不起作用......

如何解决Web服务问题:

  1. 下载并安装SoapUi并通过导入WSDL并填写所需输入来使您的SOAP请求正常工作
  2. 一旦您的请求正在运行,请安装fiddler或其他代理
  3. 将您在SoapUI中的请求的URL更改为localhost:8888或您的计算机的名称以及运行代理的端口(默认情况下,fiddler在8888上运行)。
  4. 从SoapUI发出相同的工作请求,但是新URL(localhost:8888或其他),请求将失败,但fiddler将捕获您的请求
  5. 现在在您的Android代码中,将SOAP请求的URL更改为localhost:8888并发出请求,这也将失败但fiddler将捕获您的请求
  6. 查看这两个请求并进行比较。首先查看头文件,然后查看SOAP包装器/ xml。
  7. 我已经完成了这一百万次,这是一种保证找到两个请求之间差异的方法。祝你好运!

相关问题