Java 第一次做REST服务,从android打电话
我最近开始学习android编程以及如何创建restful web服务。我为android制作了一个简单的yahtzee游戏,为了扩展我在这两个平台上的知识,我想使用restful服务实现一个两人系统 我在asp.net MVC中创建了服务,代码如下,对url/games/2的get请求将返回:Java 第一次做REST服务,从android打电话,java,c#,android,asp.net,rest,Java,C#,Android,Asp.net,Rest,我最近开始学习android编程以及如何创建restful web服务。我为android制作了一个简单的yahtzee游戏,为了扩展我在这两个平台上的知识,我想使用restful服务实现一个两人系统 我在asp.net MVC中创建了服务,代码如下,对url/games/2的get请求将返回: <Game> <Id>2</Id> <p1>100</p1> <p2>99</p2> &l
<Game>
<Id>2</Id>
<p1>100</p1>
<p2>99</p2>
<turn>1</turn>
</Game>
但我不知道如何传递参数。我服务中的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; }
}
}
控制器,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);
}
}
}
名称空间YahtzTest.Controllers
{
公共类游戏控制器:ApiController
{
静态只读igamrepository repository=新游戏存储库();
公共IEnumerable GetAllGames()
{
返回repository.GetAll();
}
公共游戏GetGame(int id)
{
游戏项目=存储库。获取(id);
如果(项==null)
{
抛出新的HttpResponseException(HttpStatusCode.NotFound);
}
退货项目;
}
公共HttpResponseMessage赛后信息(游戏项目)
{
item=存储库。添加(item);
var response=Request.CreateResponse(HttpStatusCode.Created,item);
字符串uri=Url.Link(“DefaultApi”,新的{id=item.id});
response.Headers.Location=新Uri(Uri);
返回响应;
}
公共无效PutGame(整数id,游戏)
{
game.Id=Id;
如果(!repository.Update(游戏))
{
抛出新的HttpResponseException(HttpStatusCode.NotFound);
}
}
公共游戏(int-id)
{
游戏项目=存储库。获取(id);
如果(项==null)
{
抛出新的HttpResponseException(HttpStatusCode.NotFound);
}
删除(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;
}
}
}
名称空间YahtzTest.Models
{
接口存储
{
IEnumerable GetAll();
游戏获取(int-id);
游戏添加(游戏项目);
无效删除(int-id);
bool更新(游戏项目);
}
}
名称空间YahtzTest.Models
{
公共类GameRepository:IGameRepository
{
私人列表游戏=新列表();
私有整数_nextId=1;
公共游戏库()
{
添加(新游戏{回合=0,p1=0,p2=0});
添加(新游戏{回合=1,p1=100,p2=99});
添加(新游戏{回合=0,p1=45,p2=75});
}
公共IEnumerable GetAll()
{
返回游戏;
}
公共游戏获取(int id)
{
返回games.Find(p=>p.Id==Id);
}
公共游戏添加(游戏项目)
{
如果(项==null)
{
抛出新的异常(“项”);
}
item.Id=_nextId++;
游戏。添加(项目);
退货项目;
}
公共无效删除(int id)
{
games.RemoveAll(p=>p.Id==Id);
}
公共布尔更新(游戏项)
{
如果(项==null)
{
抛出新的异常(“项”);
}
int index=games.FindIndex(p=>p.Id==item.Id);
如果(索引==-1)
{
返回false;
}
游戏。移除(索引);
游戏。添加(项目);
返回true;
}
}
}
基本上,你可以在POST上写一个字符串。在服务器端,当收到onPostReceived时,需要从字符串重新创建对象。我不知道您想如何发送数据(内容类型),请看
如果您想将一个对象发布到您的服务器,那么您可以这样做:(JSON示例)
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;
}
}
}
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();
}