3

次のように、投稿データをWebサービスに送信し、応答を取得するために接続する方法があります。

public HttpResponse sendXMLToURL(String url, String xml, String httpClientInstanceName) throws IOException {
    HttpResponse response = null;

    AndroidHttpClient httpClient = AndroidHttpClient.newInstance(httpClientInstanceName);
    HttpPost post = new HttpPost(url);

    StringEntity str = new StringEntity(xml);
    str.setContentType("text/xml");
    post.setEntity(str);

    response = httpClient.execute(post);

    if (post != null){
        post.abort();
    }
    if (httpClient !=null){
        httpClient.close();
    }

    return response;
}

次に、フラグメントの AsyncTask で、getEntity() を使用して応答を読み取ろうとします。

HttpResponse response = xmlUtil.sendXMLToURL("url", dataXML, "getList");

            //Check if the request was sent successfully
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // Parse result to check success
                responseText = EntityUtils.toString(response.getEntity());

                if (!xmlParser.checkForSuccess(responseText, getActivity())){
                    //If webservice response is error
                    ///TODO: Error management
                    return false;
                }
            }

そして、その行に到達すると:

responseText = EntityUtils.toString(response.getEntity());

例外が発生します: java.net.SocketException: Socket closed.

この動作は常に発生するわけではなく、1 回おきに発生することもあります。

4

2 に答える 2