2012-07-06 2 views
0

xml 요청 및 xml 응답을 서버에서 보낸 및 TCP 통신을 사용하여 서버 통신 할 필요가 TCP 통신 및 xml 기반 웹 서비스에 대한 경험이 없습니다. 어느 누구도 아이디어를 가지고 ???Xml webservice 및 Tcp 통신

답변

0
  • 필요한 XML 입력을 웹 서비스의 URL에 접속 전달
  • 이것이 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 클래스

    이다 서버

로부터 XML 응답 데이터를 읽어

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; 
} 
+0

당신이 테스트를 할 수 있었다? – sunil