1

我们如何为我们的网站创建rest api,我想使用rest api将服务器与我的android应用程序连接起来。如何将那些rest api与我的android应用程序连接起来,它们背后的方法是什么。

4

1 回答 1

1

在这里,您有一个不错的 rest api,具有执行 Http POST 和 GET 的基础知识:

public class RestClient {

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

public String GetResponse()
{
    return response;
}

public int GetResponseCode()
{
    return responseCode;
}

public RestClient(String url)
{
    this.url = url;
    params = new ArrayList<NameValuePair>();
    headers = new ArrayList<NameValuePair>();
}

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

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

public void Execute(RequestType requestType) throws Exception
{
    switch(requestType)
    {
        case GET:
        {
            String combinedParams = "";
            if (!params.isEmpty())
            {
                combinedParams += "?";
                for (NameValuePair p : params)
                {
                    String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");

                    if  (combinedParams.length() > 1)
                        combinedParams += "&" + paramString;
                    else
                        combinedParams += paramString;
                }
            }
            HttpGet request = new HttpGet(url + combinedParams);

            for (NameValuePair h: headers)
                request.addHeader(h.getName(),h.getValue());

            ExecuteRequest(request, url);
            break;
        }
        case POST:
        {
            HttpPost request = new HttpPost(url);

            for (NameValuePair h : headers)
            {
                request.addHeader(h.getName(), h.getValue());
            }

            if(!params.isEmpty()){
                request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            }

            ExecuteRequest(request, url);
            break;
        }
    }
}

public void ExecuteRequest(HttpUriRequest request, String url) 
{
    HttpClient client = new DefaultHttpClient();
    HttpResponse httpResponse;
    try
    {
        httpResponse = client.execute(request);
        responseCode = httpResponse.getStatusLine().getStatusCode();

        HttpEntity entity = httpResponse.getEntity();

        if (entity != null)
        {
            InputStream in = entity.getContent();
            response = ConvertStreamToString(in);
            in.close();
        }
    }
    catch (ClientProtocolException e)  {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
        } catch (IOException e) {
        Log.e("REST_CLIENT", "Execute Request: " + e.getMessage()); 
        client.getConnectionManager().shutdown();

        e.printStackTrace();
    }       
}

private String ConvertStreamToString(InputStream in)
{
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try 
    {
        while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    }
    catch (IOException e) 
    {
        e.printStackTrace();
    } 
    finally 
    {
        try 
        {
            in.close();
        } 
        catch (IOException e) 
        {
             Log.e("REST_CLIENT", "ConvertStreamToString: " + e.getMessage());  
            e.printStackTrace();
        }
    }
    return sb.toString();
}

}

于 2013-04-20T05:36:53.640 回答