所以,我将通过iphone连接到servlet并使用HTTP。我实际上正在开发一个多人游戏,想知道如何通过HTTP get(doGet)将特定数据发送到iphone。我在iphone上使用libcurl(cocos2d-x)。
以下是我的代码设置方式:
size_t write_data(void* buffer, size_t size, size_t nmemb, void *data)
{
//do stuff with data
}
//main or some init method
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl)
{
char *data = "hi imma get=yeah";
curl_easy_setopt(curl, CURLOPT_URL, "http://whatever.com");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
res = curl_easy_perform(curl);
if(res != CURLE_OK)
{
CCLOG("WELP BETTER DO SOMETHING ERROR");
}
curl_easy_cleanup(curl);
}
那么,我想知道的是我如何在java中的doGet方法中使用响应来将字符串发送到上面定义的write_function?如同,在doGet方法中如何处理响应参数?
这里的参考是doGet方法:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
System.out.println("GET METHOD CALLED");
}
那么,现在我该如何处理将一些数据传递给write_function的响应呢?
谢谢,任何和所有输入!
答案 0 :(得分:1)
使用response的Writer,如下所示。
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// tell response what format your output is in, we select plain text here
response.setContentType("text/plain;charset=UTF-8");
// ask the response object for a Writer object
PrintWriter out = response.getWriter();
try {
// and use it like you would use System.out. Only, this stuff gets sent
//to the client
out.println("GET METHOD CALLED");
} finally {
// housekeeping: ensure that the Writer is closed when you're ready.
out.close();
}
}
在某些情况下,使用Stream更容易。这也是可能的但你永远不能同时打开Writer和OutputStream 。
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/plain;charset=UTF-8");
// ask the response object for an OutputStream object
OutputStream os = response.getOutputStream();
try {
// output some stuff, here just the characters ABC
os.write(new byte[]{65,66,67});
} finally {
os.close();
}
}
如果您想了解更多信息,网上有大量关于servlet的教程,包括Servlet chapter of the official Java EE tutorial on oracle.com