如何从Android的调用REST风格的Web服务? [英] how to call RESTful web service from android?

查看:137
本文介绍了如何从Android的调用REST风格的Web服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了使用Jersey框架和java一个REST Web服务在netbean IDE。对于每一个用户需要提供用户名和密码的要求,我知道这个认证是不好的(使用curl命令,如:卷曲-u用户名:密码-X PUT的 HTTP:// localhsot:8080 /用户

I have written a REST web service in netbean IDE using jersey framework and java. For every request the user needs to provide username and password, I know that this authentication is not good (using a curl command like: curl -u username:password -X PUT http://localhsot:8080/user).

现在我想从一个Android类调用REST Web服务。我应该怎么写?我是新来的机器人。我有使用DefaultHttpClient和CredentialUsernameAndPassword一个机器人类。但是,当我在Eclipse中运行,有时我得到一个运行时异常或SDK例外。

Now I want to call a REST web service from an android class. What should I write? I am new to android. I have an android class which uses DefaultHttpClient and CredentialUsernameAndPassword. But when I run in eclipse, sometimes I get a runtime exception or sdk exception.

请人给我的样品code和建议?

Do anyone give me sample code and suggestion?

推荐答案

这是一个示例restclient类

This is an sample restclient class

public class RestClient
{
public enum RequestMethod
{
    GET,
    POST
}
public int responseCode=0;
public String message;
public String response;
public void Execute(RequestMethod method,String url,ArrayList<NameValuePair> headers,ArrayList<NameValuePair> params) throws Exception
{
    switch (method)
    {
        case GET:
        {
            // add parameters
            String combinedParams = "";
            if (params!=null)
            {
                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);
            // add headers
            if (headers!=null)
            {
                headers=addCommonHeaderField(headers);
                for (NameValuePair h : headers)
                    request.addHeader(h.getName(), h.getValue());
            }
            executeRequest(request, url);
            break;
        }
        case POST:
        {
            HttpPost request = new HttpPost(url);
            // add headers
            if (headers!=null)
            {
                headers=addCommonHeaderField(headers);
                for (NameValuePair h : headers)
                    request.addHeader(h.getName(), h.getValue());
            }
            if (params!=null)
                request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            executeRequest(request, url);
            break;
        }
    }
}
private ArrayList<NameValuePair> addCommonHeaderField(ArrayList<NameValuePair> _header)
{
    _header.add(new BasicNameValuePair("Content-Type","application/x-www-form-urlencoded"));
    return _header;
}
private void executeRequest(HttpUriRequest request, String url)
{
    HttpClient client = new DefaultHttpClient();
    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);
            instream.close();
        }
    }
    catch (Exception e)
    { }
}

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");
        }
        is.close();
    }
    catch (IOException e)
    { }
    return sb.toString();
}

}

这篇关于如何从Android的调用REST风格的Web服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆