2011-12-18 2 views
0

У меня есть SoapBuilder класс в android, который вызывает веб-сервис. Теперь я использовал его в предыдущем приложении, и он отлично работал. Проблема с этим новым приложением заключается в том, что вместо того, чтобы я возвращал реальный ответ, я получаю то, что похоже на какие-то символы крыла. Мой веб-сервис - это .net webservice, как и мое другое приложение. Единственное отличие, которое я вижу, это то, что я использовал ssl в своем предыдущем приложении, а теперь нет. Поэтому я заменил все свои файлы ssl для сокетов на reg-сокеты и socketfactorys. Вот мой код, я получаю странные символы, когда я читаю в (BufferedReader) StringBuilder contentBuilder = new StringBuilder(contentLength);Я получаю странные символы в своем ответе вместо фактического текста

if (contentLength > 0) { 
    int readBytes = 0; 
    int c = -1; 
    while ((c = in.read()) != -1) { 
     contentBuilder.append((char) c); 
     readBytes++; 
    } 
}   

Вот весь мой код для SoapBuilder.

public class SoapBuilder { 
    private final String TAG = "SOAPBUILDER"; 
    String Server = SQBApplication.SOAP_SERVER; 
    String WebServicePath = SQBApplication.SOAP_WEBSERVICEPATH; 
    String SoapAction = ""; 
    String MethodName = ""; 
    String XmlNamespace = SQBApplication.SOAP_XMLNAMESPACE; 
    Integer Port = SQBApplication.SOAP_PORT; 
    Integer BufferSize = 2048; 
    // boolean IsSSL = true; 
    private ArrayList<String> ParamNames = new ArrayList<String>(); 
    private ArrayList<String> ParamData = new ArrayList<String>(); 

    public SoapBuilder(String soapMethod) { 
     MethodName = soapMethod; 
     SoapAction = XmlNamespace + MethodName; 
    } 

    public SoapBuilder(String server, String soapMethod) 
    { 
     MethodName = soapMethod; 
     SoapAction = XmlNamespace + MethodName; 
     Server = server; 
    } 

    public SoapBuilder(String server, String webServicePath, String namespace, String soapMethod) 
    { 
     MethodName = soapMethod; 
     XmlNamespace = namespace; 
     SoapAction = XmlNamespace + MethodName; 
     Server = server; 
     WebServicePath = webServicePath; 
    } 

    public void AddParameter(String Name, String Data) { 
     ParamNames.add(Name); 
     ParamData.add(Data); 
    } 

    public String sendRequest() throws Exception { 
     String retval = ""; 
     String message = ""; 

     StringBuilder postAction = new StringBuilder(); 
     // send an HTTP request to the web service 
     postAction.append("POST " + WebServicePath + " HTTP/1.1\n"); 
     postAction.append("Content-Type: text/xml; charset=utf-8\n"); 
     postAction.append("SOAPAction: \"" + SoapAction + "\"\n"); 
     postAction.append("Host: " + Server + ":" + Port + "\n"); 
     postAction.append("Content-Length: %s\n"); 
     postAction.append("Expect: 100-continue\n"); 
     postAction.append("Accept-Encoding: gzip, deflate\n"); 
     postAction.append("Connection: Close\n"); 
     postAction.append("\n"); 
     ArrayList<String> envelope = new ArrayList<String>(); 
     envelope.add("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">"); 
     envelope.add("<s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">"); 
     envelope.add("<" + MethodName + " xmlns=\"" + XmlNamespace + "\">"); 
     // Parameters passed to the method are added here 
     for (int t = 0; t < ParamNames.size(); t++) { 
      String name = (String) ParamNames.get(t); 
      String data = (String) ParamData.get(t); 
      envelope.add("<" + name + ">" + data + "</" + name + ">"); 
     } 
     envelope.add("</" + MethodName + ">"); 
     envelope.add("</s:Body>"); 
     envelope.add("</s:Envelope>"); 

     int si = 0; 
     for (int i = 0; i < envelope.size(); i++) { 
      si += envelope.get(i).length(); 
     } 

     StringBuilder bodyBuilder = new StringBuilder(si); 
     for (int i = 0; i < envelope.size(); i++) { 
      bodyBuilder.append(envelope.get(i)); 
     } 
     message = String.format(postAction.toString(), 
     Integer.toString(bodyBuilder.length())); 
     message += bodyBuilder.toString(); 
     Socket socket = null; 
     boolean autoflush = true; 
     try { 
      SocketFactory socketFactory = (SocketFactory) SocketFactory 
       .getDefault(); 
      socket = (Socket) socketFactory.createSocket(Server, Port); 
      PrintWriter out = new PrintWriter(socket.getOutputStream(), 
      autoflush); 

      System.out.println("request length: " + message.length()); 
      if(message.length() > Integer.MAX_VALUE) 
      { 
       throw new IOException("message length exceeds max size"); 
      } 
      socket.setSendBufferSize(message.length()); 
      //only except if the message wouldn't have succeeded anyway 
      if(socket.getSendBufferSize() < message.length() && socket.getSendBufferSize() != message.length()) 
      { 
       throw new Exception(); 
      } 

      out.print(message); 
      out.flush(); 

     } catch (Exception e) { 

     } 

     BufferedReader in = new BufferedReader(new InputStreamReader(
     socket.getInputStream(), "UTF-8"), BufferSize); 
     StringBuilder response = new StringBuilder(); 

     int ci; 

     Pattern httpPattern = Pattern.compile(
      "HTTP/1.\\d\\s+(\\d+)\\s+[\\w\\s]+\\r\\n", 
      Pattern.CASE_INSENSITIVE); 
     Pattern contentLengthPattern = Pattern.compile(
      "Content-Length\\:\\s*(\\d+)\\r\\n", 
      Pattern.CASE_INSENSITIVE); 
     int contentLength = -1; 
     String httpResponse = ""; 
     while ((ci = in.read()) != -1) { 
      response.append((char) ci); 
      Matcher lengthMatcher = contentLengthPattern.matcher(response 
       .toString()); 
      Matcher httpMatcher = httpPattern.matcher(response.toString()); 

      if (lengthMatcher.find()) { 
       contentLength = Integer.parseInt(lengthMatcher.group(1)); 
      } 
      if (httpMatcher.find()) { 
       httpResponse = httpMatcher.group(1); 
      } 

      if (contentLength > 0) { 
       // contentLength+=2; 
       break; 
      } 
     } 

     StringBuilder contentBuilder = new StringBuilder(contentLength); 
     if (contentLength > 0) { 
      int readBytes = 0; 
      int c = -1; 
      while ((c = in.read()) != -1) { 
       contentBuilder.append((char) c); 
       readBytes++; 
      } 

     } 

     System.out.println(httpResponse); 
     if (httpResponse.equals("200")) { 

      Pattern responsePattern = Pattern.compile(
       "<soap:Envelope.*?>(.+)</soap:Envelope>", 
       Pattern.CASE_INSENSITIVE | Pattern.DOTALL 
       | Pattern.MULTILINE); 

      Pattern responseNullPattern = Pattern.compile("<" + MethodName 
       + "Response.+?/>", Pattern.CASE_INSENSITIVE 
       | Pattern.DOTALL | Pattern.MULTILINE); 
      Matcher responseMatcher = responsePattern 
       .matcher(contentBuilder); 
      Matcher responseNullMatcher = responseNullPattern 
       .matcher(contentBuilder); 
      System.out.println(contentBuilder); 
      if (responseMatcher.find()) { 
       retval = responseMatcher.group(0);// responseMatcher.group(0); 
      } else if (responseNullMatcher.find()) { 
       retval = null; 
      } 
     } else if (httpResponse.equals("500")) { 
      Pattern faultPattern = Pattern.compile(
       "<soap.Fault.+?>(.+)</soap.Fault>", 
       Pattern.CASE_INSENSITIVE | Pattern.DOTALL 
       | Pattern.MULTILINE); 
      Matcher faultMatcher = faultPattern.matcher(contentBuilder); 
      faultMatcher.find(); 
      retval = faultMatcher.group(0); 
     } else { 
      throw new Exception(String.format(
       "HTTP response not recognized: %s", httpResponse)); 
     } 

     in.close(); 
     socket.close(); 
     return retval; 
    } 
} 
+0

Показать фактическую, некорректные данные (шестигранный, а не символы) возвращаемой вместе с ожидаемыми. –

+0

Что, на что они похожи. В основном крыланы – user638049

+0

Хед-дамп, а не символы, пожалуйста. –

ответ

0

Я могу в значительной степени гарантировать, что это связано с проблемой кодирования. Wycats написал отличный пост по этому вопросу, который вы должны прочитать (игнорировать специфику Ruby):

http://yehudakatz.com/2010/05/05/ruby-1-9-encodings-a-primer-and-the-solution-for-rails/

+0

ОК, мое определение webservice ожидает, что запрос будет UTF-8, и, как вы можете видеть выше, мой soapbuilder использует UTF-8, чтобы они были одинаковыми. – user638049

+0

Независимо от того, что это не означает, что каждое звено в цепочке также использует UTF-8 –

+0

, так почему бы ему работать с моим последним веб-сервисом, а не с этим. Какие другие части цепи я должен проверить на основе вышеупомянутого soapbuilder? – user638049