[英]Migrating from SOAP to REST
我有一個與C#網絡服務通信的Android項目。 通信通過HTTPPost(SOAP方式)進行。 我將xml形式的請求發送到服務器,並以xml形式獲取XML形式的響應。 我正在使用以下方法進行通信:
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;
}
現在,我想將此肥皂代碼移至REST。 為此,我需要修改什么? 我需要在c#Web服務項目上進行任何更改嗎? 請說明如何遷移到RestFul服務。
首先請閱讀什么是REST,什么是RestFul: RESTful編程到底是什么?
總而言之,這意味着網址將更改。 不管使用XML還是JSON,都可以快速切換它。
另一件事是,我認為您不應對字符串對象進行操作,而應對可序列化對象進行操作,例如:
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
}
為了避免手動創建代碼,您可以將http://projects.spring.io/spring-android/或Android HTTP客戶端以及Gson或其他庫一起簽出。 某些演示(用於檢查代碼)可以在以下網址找到: https : //bitbucket.org/bartosz_bednarek/easy-android-and-java-http-client-for-soap-and-restful-api/wiki/Home 。適用於Xml或JSON在Spring庫中有支持,或者您可以找到其他庫。
如果您希望手動創建HTTP客戶端代碼,則有很多可移植性,例如:
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());
}
}
得到:
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高出可能不是最好的解決方案,因為您必須自己關心授權並記住超時,但這是命題之一。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.