gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:48:42 24 4
gpt4 key购买 nike

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

我在 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")

但我不知道如何传递参数。我的服务中的 Post 方法采用游戏对象作为参数。如果有人能给我任何建议,我将不胜感激。

模型,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;
}
}
}

最佳答案

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

如果你想将一个对象 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();
}

关于java - 第一次制作REST服务,从android调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24425619/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com