第一次制作REST服务,从android调用

时间:2014-06-26 08:18:11

标签: java c# android asp.net rest

我最近开始学习android编程以及如何创建一个宁静的Web服务。我为Android做了一个简单的yahtzee游戏,并在两个平台上扩展我的知识,我想用一个宁静的服务来实现一个双人系统。

我在asp.net MVC中使用下面的代码创建了服务,其中url / games / 2的get请求将返回:

<Game>
   <Id>2</Id>
   <p1>100</p1>
    <p2>99</p2>
    <turn>1</turn>
</Game>

我想做的就是通过调用Post创建一个新游戏,然后使用Get检查轮到你是否轮到你轮到你使用Put来更新游戏,改变你的分数和转弯所以其他玩家得到的请求会让他们的客户知道轮到他们了。我知道这对于2个玩家的功能来说是非常基本的,但这正是我正在努力学习的过程。我在Android中有一个游戏对象,但我不知道如何继续。我目前正在研究的方向是HttpClient,帖子看起来像是:

HttpPost httpPost = new HttpPost("url/games")

但我没有看到如何传递参数。我的服务中的My Post方法将游戏对象作为参数。如果有人能给我任何建议我会非常感激。

Model,Game.cs:

namespace YahtzTest.Models
{
    public class Game
    {
        public int Id { get; set; }
        public int turn { get; set; }
        public int p1 { get; set; }
        public int p2 { get; set; }
    }
}

Controller,GamesController.cs:

    namespace YahtzTest.Controllers
{
    public class GamesController : ApiController
    {
        static readonly IGameRepository repository = new GameRepository();

        public IEnumerable<Game> GetAllGames()
        {
            return repository.GetAll();
        }

        public Game GetGame(int id)
        {
            Game item = repository.Get(id);
            if (item == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return item;
        }

        public HttpResponseMessage PostGame(Game item)
        {
            item = repository.Add(item);
            var response = Request.CreateResponse<Game>(HttpStatusCode.Created, item);

            string uri = Url.Link("DefaultApi", new { id = item.Id });
            response.Headers.Location = new Uri(uri);
            return response;
        }

        public void PutGame(int id, Game game)
        {
            game.Id = id;
            if (!repository.Update(game))
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
        }

        public void DeleteGame(int id)
        {
            Game item = repository.Get(id);
            if (item == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            repository.Remove(id);
        }

    }
}

我遵循的教程中包含的其他几个文件用于存储我的游戏,GameRepository.cs和IGameRepository.cs:

    namespace YahtzTest.Models
{
    interface IGameRepository
    {
        IEnumerable<Game> GetAll();
        Game Get(int id);
        Game Add(Game item);
        void Remove(int id);
        bool Update(Game item);
    }
}


    namespace YahtzTest.Models
{
    public class GameRepository : IGameRepository
    {
        private List<Game> games = new List<Game>();
        private int _nextId = 1;

        public GameRepository()
        {
            Add(new Game { turn = 0, p1 = 0, p2 = 0 });
            Add(new Game { turn = 1, p1 = 100, p2 = 99 });
            Add(new Game { turn = 0, p1 = 45, p2 = 75 });
        }



        public IEnumerable<Game> GetAll()
        {
            return games;
        }

        public Game Get(int id)
        {
            return games.Find(p => p.Id == id);
        }

        public Game Add(Game item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            item.Id = _nextId++;
            games.Add(item);
            return item;
        }

        public void Remove(int id)
        {
            games.RemoveAll(p => p.Id == id);
        }

        public bool Update(Game item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            int index = games.FindIndex(p => p.Id == item.Id);
            if (index == -1)
            {
                return false;
            }
            games.RemoveAt(index);
            games.Add(item);
            return true;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

基本上你在POST上写一个字符串。在服务器端,当onPostReceived时,您需要从字符串重新创建对象。我不知道你想如何发送你的数据(Content-Type),看看

如果要将对象POST到服务器,那么可以这样做:(JSON示例)

        HttpClient httpClient = HttpHelper.getHttpClient();
        HttpPost httppost = new HttpPost("yourServerAddress");
        httppost.setHeader("Accept", "application/json; charset=utf-8");
        httppost.setHeader("Content-type", "application/json; charset=utf-8");

        // StringEntity
        String inStr = yourObject.toString();
        StringEntity se = new StringEntity(inStr, HTTP.UTF_8);

        // Params
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, HTTP.UTF_8);
        httppost.setParams(params);         
        httppost.setEntity(se);

        // Fire and read response
        HttpResponse response = httpclient.execute(httppost);

        // read answer
        String content = null;
        InputStream stream = null;
        try {
            if (response != null) {
                stream = response.getEntity().getContent();
                InputStreamReader reader = new InputStreamReader(stream, HTTP.UTF_8);
                BufferedReader buffer = new BufferedReader(reader);
                StringBuilder sb = new StringBuilder();
                String cur;
                while ((cur = buffer.readLine()) != null) {
                    sb.append(cur);
                }
                //here's your whole response from your server if you provide any
                content = sb.toString();
            }
        } finally {
            if (stream != null) {
                stream.close();
            }
        }           

    } catch (Exception e) {
        e.printStackTrace();
    }