安卓:网络服务

发布于 2024-12-11 07:16:19 字数 310 浏览 0 评论 0原文

我想创建一个 Android 应用程序(客户端服务器),它将与已经运行的 Web 服务器交互。

我决定使用 REST 而不是 SOAP

这是我的两个问题:

1。哪种数据格式更可靠且易于使用? JSON开放数据协议 (odata.org)
2。如何在服务器和应用程序之间进行首次通信?

我需要调用服务器,然后获得响应(只是为了测试连接)。 请包含一些代码作为示例或我可以学习更多信息的链接!

I want to create an Android App (client-server) that will interact with already running web server.

I have decided to use REST as opposed to SOAP.

Here are my 2 questions:

1 .What data format is more reliable and simple to use? JSON or Open Data protocol (odata.org) ?
2. How do I make the first communication between the server and the app?

I need to call the server, and then get a response (just to test the connection).
Please include some code as an example or a link to where I can lern more!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你的往事 2024-12-18 07:16:19

我肯定会选择 JSON,因为它更常用。至于在 Android 上设计 RESTful 应用程序,我会从 Android RESTful 查看一般概念,并查看那些对我有帮助的代码:Android RESTful API 服务

I would definately go with JSON as it is more commonly used. As for designing RESTful apps on android I would start with Android RESTful to see the general concept and would take a look at those code bits that helped me out: Android RESTful API Service

孤独陪着我 2024-12-18 07:16:19

调用 RESTful Web 服务

public class RestClient {
private boolean authentication;
private ArrayList<NameValuePair> headers;

private String jsonBody;
private String message;

private ArrayList<NameValuePair> params;
private String response;
private int responseCode;

private String url;

// HTTP Basic Authentication
private String username;
private String password;

protected Context context;

public RestClient(String url) {
    this.url = url;
    params = new ArrayList<NameValuePair>();
    headers = new ArrayList<NameValuePair>();
}
//Be warned that this is sent in clear text, don't use basic auth unless you have to.
public void addBasicAuthentication(String user, String pass) {
    authentication = true;
    username = user;
    password = pass;
}

public void addHeader(String name, String value) {
    headers.add(new BasicNameValuePair(name, value));
}

public void addParam(String name, String value) {
    params.add(new BasicNameValuePair(name, value));
}

public void execute(RequestMethod method)
    throws Exception {
    switch (method) {
        case GET: {
            HttpGet request = new HttpGet(url + addGetParams());
            request = (HttpGet) addHeaderParams(request);
            executeRequest(request, url);
            break;
        }
        case POST: {
            HttpPost request = new HttpPost(url);
            request = (HttpPost) addHeaderParams(request);
            request = (HttpPost) addBodyParams(request);
            executeRequest(request, url);
            break;
        }
        case PUT: {
            HttpPut request = new HttpPut(url);
            request = (HttpPut) addHeaderParams(request);
            request = (HttpPut) addBodyParams(request);
            executeRequest(request, url);
            break;
        }
        case DELETE: {
            HttpDelete request = new HttpDelete(url);
            request = (HttpDelete) addHeaderParams(request);
            executeRequest(request, url);
        }
    }
}

private HttpUriRequest addHeaderParams(HttpUriRequest request)
        throws Exception {
    for (NameValuePair h : headers) {
        request.addHeader(h.getName(), h.getValue());
    }

    if (authentication) {

        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(
                username, password);
        request.addHeader(new BasicScheme().authenticate(creds, request));
    }

    return request;
}

private HttpUriRequest addBodyParams(HttpUriRequest request)
        throws Exception {
    if (jsonBody != null) {
        request.addHeader("Content-Type", "application/json");
        if (request instanceof HttpPost)
            ((HttpPost) request).setEntity(new StringEntity(jsonBody,
                    "UTF-8"));
        else if (request instanceof HttpPut)
            ((HttpPut) request).setEntity(new StringEntity(jsonBody,
                    "UTF-8"));

    } else if (!params.isEmpty()) {
        if (request instanceof HttpPost)
            ((HttpPost) request).setEntity(new UrlEncodedFormEntity(params,
                    HTTP.UTF_8));
        else if (request instanceof HttpPut)
            ((HttpPut) request).setEntity(new UrlEncodedFormEntity(params,
                    HTTP.UTF_8));
    }
    return request;
}

private String addGetParams()
    throws Exception {
    StringBuffer combinedParams = new StringBuffer();
    if (!params.isEmpty()) {
        combinedParams.append("?");
        for (NameValuePair p : params) {
            combinedParams.append((combinedParams.length() > 1 ? "&" : "")
                    + p.getName() + "="
                    + URLEncoder.encode(p.getValue(), "UTF-8"));
        }
    }
    return combinedParams.toString();
}

public String getErrorMessage() {
    return message;
}

public String getResponse() {
    return response;
}

public int getResponseCode() {
    return responseCode;
}

public void setContext(Context ctx) {
    context = ctx;
}

public void setJSONString(String data) {
    jsonBody = data;
}

private void executeRequest(HttpUriRequest request, String url) {

    DefaultHttpClient client = new DefaultHttpClient();
    HttpParams params = client.getParams();

    // Setting 30 second timeouts
    HttpConnectionParams.setConnectionTimeout(params, 30 * 1000);
    HttpConnectionParams.setSoTimeout(params, 30 * 1000);

    HttpResponse httpResponse;

    try {
        httpResponse = client.execute(request);
        responseCode = httpResponse.getStatusLine().getStatusCode();
        message = httpResponse.getStatusLine().getReasonPhrase();

        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {

            InputStream instream = entity.getContent();
            response = convertStreamToString(instream);

            // Closing the input stream will trigger connection release
            instream.close();
        }

    } catch (ClientProtocolException e) {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
    } catch (IOException e) {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
    }
}

private static String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

}

calling RESTful web service

public class RestClient {
private boolean authentication;
private ArrayList<NameValuePair> headers;

private String jsonBody;
private String message;

private ArrayList<NameValuePair> params;
private String response;
private int responseCode;

private String url;

// HTTP Basic Authentication
private String username;
private String password;

protected Context context;

public RestClient(String url) {
    this.url = url;
    params = new ArrayList<NameValuePair>();
    headers = new ArrayList<NameValuePair>();
}
//Be warned that this is sent in clear text, don't use basic auth unless you have to.
public void addBasicAuthentication(String user, String pass) {
    authentication = true;
    username = user;
    password = pass;
}

public void addHeader(String name, String value) {
    headers.add(new BasicNameValuePair(name, value));
}

public void addParam(String name, String value) {
    params.add(new BasicNameValuePair(name, value));
}

public void execute(RequestMethod method)
    throws Exception {
    switch (method) {
        case GET: {
            HttpGet request = new HttpGet(url + addGetParams());
            request = (HttpGet) addHeaderParams(request);
            executeRequest(request, url);
            break;
        }
        case POST: {
            HttpPost request = new HttpPost(url);
            request = (HttpPost) addHeaderParams(request);
            request = (HttpPost) addBodyParams(request);
            executeRequest(request, url);
            break;
        }
        case PUT: {
            HttpPut request = new HttpPut(url);
            request = (HttpPut) addHeaderParams(request);
            request = (HttpPut) addBodyParams(request);
            executeRequest(request, url);
            break;
        }
        case DELETE: {
            HttpDelete request = new HttpDelete(url);
            request = (HttpDelete) addHeaderParams(request);
            executeRequest(request, url);
        }
    }
}

private HttpUriRequest addHeaderParams(HttpUriRequest request)
        throws Exception {
    for (NameValuePair h : headers) {
        request.addHeader(h.getName(), h.getValue());
    }

    if (authentication) {

        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(
                username, password);
        request.addHeader(new BasicScheme().authenticate(creds, request));
    }

    return request;
}

private HttpUriRequest addBodyParams(HttpUriRequest request)
        throws Exception {
    if (jsonBody != null) {
        request.addHeader("Content-Type", "application/json");
        if (request instanceof HttpPost)
            ((HttpPost) request).setEntity(new StringEntity(jsonBody,
                    "UTF-8"));
        else if (request instanceof HttpPut)
            ((HttpPut) request).setEntity(new StringEntity(jsonBody,
                    "UTF-8"));

    } else if (!params.isEmpty()) {
        if (request instanceof HttpPost)
            ((HttpPost) request).setEntity(new UrlEncodedFormEntity(params,
                    HTTP.UTF_8));
        else if (request instanceof HttpPut)
            ((HttpPut) request).setEntity(new UrlEncodedFormEntity(params,
                    HTTP.UTF_8));
    }
    return request;
}

private String addGetParams()
    throws Exception {
    StringBuffer combinedParams = new StringBuffer();
    if (!params.isEmpty()) {
        combinedParams.append("?");
        for (NameValuePair p : params) {
            combinedParams.append((combinedParams.length() > 1 ? "&" : "")
                    + p.getName() + "="
                    + URLEncoder.encode(p.getValue(), "UTF-8"));
        }
    }
    return combinedParams.toString();
}

public String getErrorMessage() {
    return message;
}

public String getResponse() {
    return response;
}

public int getResponseCode() {
    return responseCode;
}

public void setContext(Context ctx) {
    context = ctx;
}

public void setJSONString(String data) {
    jsonBody = data;
}

private void executeRequest(HttpUriRequest request, String url) {

    DefaultHttpClient client = new DefaultHttpClient();
    HttpParams params = client.getParams();

    // Setting 30 second timeouts
    HttpConnectionParams.setConnectionTimeout(params, 30 * 1000);
    HttpConnectionParams.setSoTimeout(params, 30 * 1000);

    HttpResponse httpResponse;

    try {
        httpResponse = client.execute(request);
        responseCode = httpResponse.getStatusLine().getStatusCode();
        message = httpResponse.getStatusLine().getReasonPhrase();

        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {

            InputStream instream = entity.getContent();
            response = convertStreamToString(instream);

            // Closing the input stream will trigger connection release
            instream.close();
        }

    } catch (ClientProtocolException e) {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
    } catch (IOException e) {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
    }
}

private static String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

}

静赏你的温柔 2024-12-18 07:16:19

与 XML 相比,JSON 易于构建和实现。

以下是使用 HttpClient 执行 HTTP POST 请求

这是给出的最佳问题和答案: 使用 android 发出 HTTP 请求

从 Android 调用 REST Web 服务

更新:

这适合您使用 JSON 请求进行 REST Web 服务调用的要求:调用休息网络服务?

JSON is easy to construct and easy to implement as compared to XML.

Here is code snippets for Executing a HTTP POST Request with HttpClient

Here is the best Question with Answer given: Make an HTTP request with android

Calling a REST web service from Android

Update:

This one suits your requirement to make a REST webservice call with JSON request: calling rest web service?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文