2014-04-15 66 views
0

我有一個與C#webservices通信的Android項目。通信通過HTTPPost(SOAP方式)進行。我以xml的形式向服務器發送請求,並以xml形式獲取XML格式的響應。我正在使用以下方法進行通信:從SOAP遷移到REST

public static BasicHttpResponse getResponse(String uri, 
      String SOAPRequestXML) throws ClientProtocolException, Exception { 

     HttpPost httppost = new HttpPost(uri); 

     StringEntity se = null; 
     try { 
      se = new StringEntity(SOAPRequestXML, HTTP.UTF_8); 
     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } 

     se.setContentType("Text/Xml"); 
     httppost.setHeader("Content-Type", "Text/Xml"); 

     httppost.setEntity(se); 

     HttpClient httpclient = new DefaultHttpClient(); 
     BasicHttpResponse httpResponse = null; 

     httpResponse = (BasicHttpResponse) httpclient.execute(httppost); 

     return httpResponse; 
    } 

現在我想將此soap代碼移到REST。爲此我需要修改?我是否需要更改我的c#webservice項目上的任何內容?請解釋我如何遷移到RestFul服務。

回答

0

首先,請閱讀什麼是REST,什麼也意味着REST風格: What exactly is RESTful programming?

在多總結這意味着網址將會改變。無論您使用XML還是JSON,都應該可以快速切換它。

另一件事是,在我看來,你不應該對String對象,但像序列化對象進行操作:

Class ContainerWithData implements Serializable { 

private Integer a; 

private Integet b; 

private String c; 

//remeber that it can be null values up here 

//Getters and settes below 

} 

爲了避免手動創建代碼,你可以用GSON或沿退房http://projects.spring.io/spring-android/或Android HTTP客戶端其他圖書館。一些演示(查看代碼,可以發現:。https://bitbucket.org/bartosz_bednarek/easy-android-and-java-http-client-for-soap-and-restful-api/wiki/Home對於XML或JSON有支撐在Spring庫中,也可以找到其他圖書館

如果你想碼的手動創建HTTP客戶端代碼有很多pissibilities的,例如:

Mayby這樣的界面將幫助您:

interface SimpleHttpClient { 
    <T> T get(String url, Class<T> classe) throws IOException; 
    <T> T post(String url, Class<T> classe, Serializable contentOrJson) throws IOException; 
    <T> T put(String url, Class<T> classe, Serializable contentOrJson) throws IOException; 
    void delete(String url, Serializable contentOrJson) throws IOException; 
} 

在有可能有例如:

public abstract class EasyHttpClient implements SimpleHttpClient { 

     private EasyHttpClientRequest request = new EasyHttpClientRequest(); 
    private EasyHttpClientGetRequest requestToGet = new EasyHttpClientGetRequest(); 

    protected synchronized String get(String url) throws IOException { 
     return requestToGet.getRequest(url); 
    } 

    protected synchronized String post(String url, String contentOrJson) 
      throws IOException { 
     return request.doReguest(url, contentOrJson, "POST", getMimeType()); 
    } 

    protected synchronized String put(String url, String contentOrJson) 
      throws IOException { 
     return request.doReguest(url, contentOrJson, "PUT", getMimeType()); 
    } 

    protected synchronized void deleteRequest(String url, String contentOrJson) throws IOException { 
     request.doReguest(url, contentOrJson, "DELETE", getMimeType()); 
    } 
} 

GET:

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.Reader; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.nio.charset.Charset; 

public class EasyHttpClientGetRequest { 

    public String getRequest(String url) throws MalformedURLException, IOException{ 
     InputStream is = new URL(url).openStream(); 
     try { 
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, 
        Charset.forName("UTF-8"))); 
      String jsonText = readAll(rd); 
      return jsonText; 
     } finally { 
      is.close(); 
     } 
    } 

    /** 
    * Will get {@link String} from {@link Reader} assuming that {@link Byte} in 
    * {@link Reader} are char representation. 
    */ 
    private synchronized String readAll(Reader rd) throws IOException { 
     StringBuilder sb = new StringBuilder(); 
     int cp; 
     while ((cp = rd.read()) != -1) { 
      sb.append((char) cp); 
     } 
     return sb.toString(); 
    } 
} 

其他類似的POST/PUT/DELETE:

import java.io.BufferedReader; 
import java.io.DataOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.ProtocolException; 
import java.net.URL; 

public final class EasyHttpClientRequest { 

    /** 
    * Will perform HTTP request to server based on the parameters that has been 
    * declared. 
    * 
    * @param url 
    *   - URL for connect to. 
    * @param contentOrJson 
    *   - content in String or JSON format 
    * @param method 
    *   - "DELETE"/"POST"/"PUT" for sending data. 
    * @param mime 
    *   - mime type in format of Content-Type. 
    * @return content of the request as String or null if no content. 
    * @throws IOException 
    *    if there will be error during communication. 
    */ 
    public synchronized String doReguest(String url, String contentOrJson, String method, String mime) 
      throws IOException { 
     URL url1; 
     HttpURLConnection connection = null; 
     try { 

      // Create connection 
      url1 = new URL(url); 
      connection = (HttpURLConnection) url1.openConnection(); 
      connection.setRequestMethod(method); 
      connection.setRequestProperty("Content-Type", mime); 

      connection.setRequestProperty("Content-Length", 
        "" + Integer.toString(contentOrJson.getBytes().length)); 
      connection.setRequestProperty("Content-Language", "en-US"); 

      connection.setUseCaches(false); 
      connection.setDoInput(true); 
      connection.setDoOutput(true); 

      // Send request 
      DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); 
      wr.writeBytes(contentOrJson); 
      wr.flush(); 
      wr.close(); 

      // Get Response 
      InputStream is = connection.getInputStream(); 
      BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 
      String line; 
      StringBuffer response = new StringBuffer(); 
      while ((line = rd.readLine()) != null) { 
       response.append(line); 
       response.append('\r'); 
      } 
      rd.close();   
      return response.toString(); 

     } catch (ProtocolException e) { 
      return checkProtocolOrReturn(method); 
     } catch (Exception e) { 
      throw new IOException("Invalid!"); 
     } finally { 
      tryToCloseConnection(connection); 
     } 
    } 



    /** 
    * Checks if method is "DELETE" or returns null. It is done bcs DELETE has 
    * no content. Invoked after {@link ProtocolException} 
    * 
    * @param method 
    *   representation ex. "DELETE" 
    * @return null if not Delete. 
    * @throws IOException 
    */ 
    private String checkProtocolOrReturn(String method) throws IOException { 
     if (!method.equals("DELETE")) { 
      throw new IOException("Invalid!"); 
     } else { 
      return null; 
     } 
    } 

    /** 
    * Will try to close connection if it is not closed already. 
    * 
    */ 
    private void tryToCloseConnection(HttpURLConnection connection) { 
     if (connection != null) { 
      connection.disconnect(); 
     } 
    } 
} 

的URL上了例如mayby是不是最好的解決方案,你必須自己和remeber約在意授權超時但這是命題之一。

+0

字符串是可串行化的。 –

+0

@EricStein - 我沒有提到字符串不是可序列化的 - 它們確實是。但更好的做法是使用容器序列化對象,而不是在請求時計劃字符串。 – elektronika