2012-02-22 3 views
2

아래 코드를 통해 웹 서비스에 게시하는 Android 앱이 있는데 제대로 작동합니다. 그러나 서비스의 myContract 메소드는 부울 (true 또는 false)을 반환합니다. 내 앱이 false로 이동할지 여부를 알 수 있도록 그 값을 검색하려면 어떻게해야합니까? 편집에 대한 미안하지만, HttpResponse에를 사용하여, 다음 로그인하거나 response.toString()을 토스트WCF에서 안드로이드가 반환 값을 가져옵니다.

HttpPost request = new HttpPost(SERVICE_URI + "/myContract/someString"); 

request.setHeader("Accept", "application/json"); 
request.setHeader("Content-type", "application/json"); 

DefaultHttpClient httpClient = new DefaultHttpClient(); 
HttpResponse response = httpClient.execute(request); 

편집

내가 이해할 수없는 문자열을 반환합니다!

업데이트

감사 Shereef,

하지만 그건 좀 너무 많은 정보와 내가하려고했던 일을하는 코드처럼 보인다. 그 아래에 몇 가지 코드를 추가했는데 맞는지 확실하지 않습니다. 이 서비스는 POST가 성공했는지 여부에 대한 부울을 true 또는 false로 반환하지만 문자열로 검색하는 것처럼 보입니다!

HttpEntity responseEntity = response.getEntity(); 

char[] buffer = new char[(int)responseEntity.getContentLength()]; 
InputStream stream = responseEntity.getContent();  
InputStreamReader reader = new InputStreamReader(stream); 
reader.read(buffer); 
stream.close(); 

JSONObject jsonResponse = new JSONObject(new String(buffer));   
String ServiceResponse = jsonResponse.getString("putCommuniqueResult"); 

Log.d("WebInvoke", "Saving : " + ServiceResponse); 

괜찮습니까? 그것은 작동하지만 그 권리가 있는지 확실하지 않습니다! 건배, 마이크.

+0

웹 서비스는 당신이 읽을 수있는 동일한 기술을 사용하지 않는, 모든 프로그래밍 언어와 통신 할 수 있도록 설계이 답변을 참조 할 수 있습니다 XML 또는 JSON을 사용하여 데이터를 얻을 필요가있는 경우) 당신은 항상 문자열로 읽고 당신이 필요로하는 타겟 포맷으로 파싱한다. 예를 들어 C#은 웹 서비스 레퍼런스를 추가 할 수 있고 wsdl을 파싱하는 라이브러리를 얻지 않는다면 다른 포맷으로 데이터를 얻을 수있다. 그런 다음 wcf 문자열을 실제 출력으로 구문 분석합니다. 구문 분석 할 때까지 항상 문자열이됩니다. –

답변

3
private static String getDataFromXML(final String text) { 
    final String temp = new String(text).split("<")[2].split(">")[1]; 
    final String temp2 = temp.replace("&lt;", "<").replace("&gt;", ">") 
      .replace("&amp;", "&"); 
    return temp2; 
} 

/** 
* Connects to the web service and returns the pure string returned, NOTE: 
* if the generated url is more than 1024 it automatically delegates to 
* connectPOST 
* 
* @param hostName 
*   : the host name ex: google.com or IP ex: 
*   127.0.0.1 
* @param webService 
*   : web service name ex: TestWS 
* @param classOrEndPoint 
*   : file or end point ex: CTest 
* @param method 
*   : method being called ex: TestMethod 
* @param parameters 
*   : Array of {String Key, String Value} ex: { { "Username", 
*   "admin" }, { "Password", "313233" } } 
* @return the trimmed String received from the web service 
* 
* @author Shereef Marzouk - http://shereef.net 
* 
* 
*/ 
public static String connectGET(final String hostNameOrIP, 
     final String webService, final String classOrEndPoint, 
     final String method, final String[][] parameters) { 
    String url = "http://" + hostNameOrIP + "/" + webService + "/" 
      + classOrEndPoint + "/" + method; 
    String params = ""; 
    if (null != parameters) { 
     for (final String[] strings : parameters) { 
      if (strings.length == 2) { 
       if (params.length() != 0) { 
        params += "&"; 
       } 
       params += strings[0] + "=" + strings[1]; 
      } else { 
       Log.e(Standards.TAG, 
         "The array 'parameters' has the wrong dimensions(" 
           + strings.length + ") in " + method + "(" 
           + parameters.toString() + ")"); 
      } 
     } 
    } 
    url += "?" + params; 
    if (url.length() >= 1024) { // The URL will be truncated if it is more 
           // than 1024 
     return Communications.connectPOST(hostNameOrIP, webService, 
       classOrEndPoint, method, parameters); 
    } 
    final StringBuffer text = new StringBuffer(); 
    HttpURLConnection conn = null; 
    InputStreamReader in = null; 
    BufferedReader buff = null; 
    try { 
     final URL page = new URL(url); 
     conn = (HttpURLConnection) page.openConnection(); 
     conn.connect(); 
     in = new InputStreamReader((InputStream) conn.getContent()); 
     buff = new BufferedReader(in); 
     String line; 
     while (null != (line = buff.readLine()) && !"null".equals(line)) { 
      text.append(line + "\n"); 
     } 
    } catch (final Exception e) { 
     Log.e(Standards.TAG, 
       "Exception while getting " + method + " from " + webService 
         + "/" + classOrEndPoint + " with parameters: " 
         + params + ", exception: " + e.toString() 
         + ", cause: " + e.getCause() + ", message: " 
         + e.getMessage()); 
     Standards.stackTracePrint(e.getStackTrace(), method); 
     return null; 
    } finally { 
     if (null != buff) { 
      try { 
       buff.close(); 
      } catch (final IOException e1) { 
      } 
      buff = null; 
     } 
     if (null != in) { 
      try { 
       in.close(); 
      } catch (final IOException e1) { 
      } 
      in = null; 
     } 
     if (null != conn) { 
      conn.disconnect(); 
      conn = null; 
     } 
    } 

    if (text.length() > 0 && Communications.checkText(text.toString())) { 
     final String temp = Communications.getDataFromXML(text.toString()); 
     Log.i(Standards.TAG, "Success in " + method + "(" + params 
       + ") = " + temp); 
     return temp; 
    } 
    Log.w(Standards.TAG, "Warning: " + method + "(" + params + "), text = " 
      + text.toString()); 
    return null; 
} 

의 말을하자이 URL은 서비스가 출력을

http://google.com/wcfsvc/service.svc/showuserdata/11949

public boolean isWSTrue() { 
    String data = connectGET("google.com", 
      "wcfsvc", "service.svc", 
      "showuserdata/11949", null); 
    if(null != data && data.length() >0) 
     return data.toLowerCase().contains("true"); 
    throw new Exception("failed to get webservice data"); 
} 

주입니다 보여주고 있습니다 :에만 확인이 경우 내에서 실제로 JSON 또는 XML을 구문 분석 할 필요가 없습니다 부울 그러면 당신은 당신이 진실을 발견했는지 안다. 거짓이라면 다른 것이 발견된다.

당신은 (.NET을 당신이 https://stackoverflow.com/a/3812146/435706

+0

제 대답을 형식화했습니다. –

관련 문제