0

I have an Android project which communicates with C# webservices. The communication happens via HTTPPost(SOAP way). I send request in the form of xml's to server and get response in XML form as xml. I am using the following method for communication:

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

Now I want to move this soap code to REST. For this what I need to modify? Do I need to change anything on my c# webservice project? Please explain how can I migrate to RestFul services.

Jainendra
  • 23,305
  • 30
  • 116
  • 165

1 Answers1

0

First of all please read what is REST and what does mean RestFul: What exactly is RESTful programming?

In much summary it means the url will change. It has no matter if you use XML or JSON as it is should be possibility to switch it fast.

Other thing is that in my opinion you should not operate on String objects but on Serializable Objects like:

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

}

To avoid manually create code you can check out http://projects.spring.io/spring-android/ or Android HTTP client along with Gson or other library. Some demo (to check code can be found at: https://bitbucket.org/bartosz_bednarek/easy-android-and-java-http-client-for-soap-and-restful-api/wiki/Home. For Xml or JSON there is support in Spring library or you can find other libraries.

If you wish to mannually create HTTP Client code there are plenty of pissibilities, for example:

Mayby such interface will help you:

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

Under there there could be for example:

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();
    }
}

OTHERS like 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();
        }
    }
}

The URL upper out in example mayby is not the best solution as you have to care about Authorization by yourself and remeber about timeouts but this is one of proposition.

Community
  • 1
  • 1