0

サーバーから xml 要求と xml 応答があり、TCP 通信でサーバーと通信する必要があります。TCP 通信と xml ベースの Web サービスの経験がありません。誰でもアイデアがありますか?????

4

1 に答える 1

0
  • WebサービスのURLに接続し、必要なXML入力を渡します
  • サーバーからXML応答データを読み取ります

これはRestClientクラスです

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;

import android.content.Context;

public class RestClient {

    private static final Logger logger = Logger.getLogger("Telfaz");

    private boolean authentication;
    private ArrayList<NameValuePair> headers;

    private String jsonBody;
    private byte[] rawDataBytes;

    private String message;

    private ArrayList<NameValuePair> params;
    private String response;
    private int responseCode;

    private String url;

    // HTTP Basic Authentication
    private String username;
    private String password;

    protected Context context;

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

    // Be warned that this is sent in clear text, don't use basic auth unless
    // you have to.
    public void addBasicAuthentication(String user, String pass) {
        authentication = true;
        username = user;
        password = pass;
    }

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

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

    public void execute(RequestMethod method) throws Exception {
        switch (method) {
        case GET: {
            HttpGet request = new HttpGet(url + addGetParams());
            request = (HttpGet) addHeaderParams(request);
            executeRequest(request, url);
            break;
        }
        case POST: {
            HttpPost request = new HttpPost(url);
            request = (HttpPost) addHeaderParams(request);
            request = (HttpPost) addBodyParams(request);
            executeRequest(request, url);
            break;
        }
        case PUT: {
            HttpPut request = new HttpPut(url);
            request = (HttpPut) addHeaderParams(request);
            request = (HttpPut) addBodyParams(request);
            executeRequest(request, url);
            break;
        }
        case DELETE: {
            HttpDelete request = new HttpDelete(url);
            request = (HttpDelete) addHeaderParams(request);
            executeRequest(request, url);
        }
        }
    }

    private HttpUriRequest addHeaderParams(HttpUriRequest request)
            throws Exception {

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

        if (authentication) {

            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(
                    username, password);
            request.addHeader(new BasicScheme().authenticate(creds, request));
        }

        return request;
    }

    private HttpUriRequest addBodyParams(HttpUriRequest request)
            throws Exception {
        if (rawDataBytes != null) {
            request.addHeader("Content-Type", "application/x-gzip");
            if (request instanceof HttpPost)
                ((HttpPost) request).setEntity(new ByteArrayEntity(rawDataBytes));
        }
        else if (jsonBody != null) {
            request.addHeader("Content-Type", "application/json");
            if (request instanceof HttpPost)
                ((HttpPost) request).setEntity(new StringEntity(jsonBody,
                        "UTF-8"));
            else if (request instanceof HttpPut)
                ((HttpPut) request).setEntity(new StringEntity(jsonBody,
                        "UTF-8"));


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



        }
        return request;
    }

    private String addGetParams() throws Exception {
        StringBuffer combinedParams = new StringBuffer();
        if (!params.isEmpty()) {
            combinedParams.append("?");
            for (NameValuePair p : params) {
                combinedParams.append((combinedParams.length() > 1 ? "&" : "")
                        + p.getName() + "="
                        + URLEncoder.encode(p.getValue(), "UTF-8"));
            }
        }
        return combinedParams.toString();
    }

    public String getErrorMessage() {
        return message;
    }

    public String getResponse() {
        return response;
    }

    public int getResponseCode() {
        return responseCode;
    }

    public void setContext(Context ctx) {
        context = ctx;
    }

    public void setJSONString(String data) {
        jsonBody = data;
    }

    /**
     * Sets the rawDataBytes.
     *
     * @param rawDataBytes <tt> the rawDataBytes to set.</tt>
     */
    public void setRawDataBytes(byte[] rawDataBytes) {
        this.rawDataBytes = rawDataBytes;
    }

    private void executeRequest(HttpUriRequest request, String url) {

        DefaultHttpClient client = new DefaultHttpClient();
        HttpParams params = client.getParams();

        // Setting 30 second timeouts
        HttpConnectionParams.setConnectionTimeout(params, 30 * 1000);
        HttpConnectionParams.setSoTimeout(params, 30 * 1000);

        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 = convertInputStreamToString(instream);
                // Closing the input stream will trigger connection release
                instream.close();
            }

        } catch (ClientProtocolException e) {
            client.getConnectionManager().shutdown();
            logger.error(Util.getStackTrace(e));
        } catch (IOException e) {
            client.getConnectionManager().shutdown();
            logger.error(Util.getStackTrace(e));
        }
    }

    private static String convertInputStreamToString(InputStream is) {
        final int BUFFER_SIZE = 32;
        StringBuilder string = null;
        try {
            BufferedInputStream gis = new BufferedInputStream(is, BUFFER_SIZE);
            string = new StringBuilder();
            byte[] data = new byte[BUFFER_SIZE];
            int bytesRead;
            while ((bytesRead = gis.read(data)) != -1) {
                string.append(new String(data, 0, bytesRead));
            }
            gis.close();
            is.close();
        } catch (IOException e) {
            logger.error(Util.getStackTrace(e));
        }
        if(string == null)return null;
        return string.toString();
    }

}

このRequestMethodクラス

public enum RequestMethod {
    DELETE, GET, POST, PUT
}

そして、以下のように必要な場合はこれらのクラスを使用してください。

public String communicateWithServer(String xmlInput) {

    String response = null;
    String webServiceUrl = "your-server-url";
    RestClient client = new RestClient(webServiceUrl);
    client.setJSONString(xmlInput);
    client.addHeader("Content-Type", "text/xml");
    try {
        client.execute(RequestMethod.POST);
        if (client.getResponseCode() != 200) {
            // handle error here
        }
        response = client.getResponse();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;
}
于 2012-07-06T12:27:19.157 に答える