首先要搭建一个httpserver,这里採用tomcat6为例:

过程:新建一个Servlet,并使用tomcat的默认port号8080监听,最后写一个jsp来測试能否够訪问该server

1)新建一个Serlvet

新建完后增加写下測试代码:

public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* Default constructor.
*/
public TestServlet() {
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("test", "test");
request.getRequestDispatcher("index.jsp").forward(request, response); } }

该Servlet的名字是TestServlet。所以把web.xml中的内容改成下面内容

<?

xml version="1.0" encoding="UTF-8"?

>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>TestServlet</display-name> <servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>com.test.servlet.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/TestServlet</url-pattern>
</servlet-mapping>
</web-app>

然后编写一个訪问该Servlet后会跳转的jsp(index.jsp)

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
${test }
</body>
</html>

最后启动server。在浏览器中如输入下面地址:http://localhost:8080/TestServlet/TestServlet,能够看到訪问成功

其次在cocos2d-x项目中封装curl(參考Cocos2d-x高级开发教程,并添加了能够传输多个键值对),代码比較简单,直接在凝视中说明:

头文件:

//单线程发送,会堵塞
class NetworkAdaptor {
public:
NetworkAdaptor(const string &baseUrl);//构造
NetworkAdaptor(const char* baseUrl);//构造
bool sendValueForKey(const char* key, const char* value, string &wirteBackBuffer);//发送一个HTTP请求
bool sendValueForKey(const map<string, string> &content, string &wirteBackBuffer);//发送一个HTTP请求
private:
string m_sBaseUrl;//请求的url地址
};
//多线程线程发送
class AsynNetworkAdaptor {
public:
void sendValueForKeyToUrl(const char* key, const char* value, const string &url, string &wirteBackBuffer);//添加一个HTTP请求
void sendValueForKeyToUrl(const map<string, string> content, const string &url, string &wirteBackBuffer);//添加一个HTTP请求
void flushSendRequests();//批量发送HTTP请求 CC_SYNTHESIZE_READONLY(int, m_iUnfinishedRequest, UnfinishedRequest);//发送的数量
protected:
struct RequestInfo {//请求信息
RequestInfo(const map<string, string> &content, const string &url, string &buffer) : content(content), url(url), buffer(buffer){}
map<string, string> content;//发送内容
string url;//请求的url地址
string &buffer;//server回传的内容
};
vector<RequestInfo> requests;//请求容器
};

cpp文件:

//将键值对的内容转换成表单格式的内容进行传送
void translate(const map<string, string> &content, string &sendout) {
sendout = "";
for(map<string, string>::const_iterator it = content.begin(); it != content.end(); ++it) {
sendout = sendout + (it->first + "=" + it->second) + "&";
}
sendout = sendout.substr(0, sendout.length() - 1);//去掉最后一个&字符
}
//回调函数。一定要返回服务器对应过来的字节大小
size_t writer(char* data, size_t size, size_t number, string* writeData) {
if(writeData == NULL) {
return 0;
}
writeData->append(data, size * number);
return size * number;
} NetworkAdaptor::NetworkAdaptor(const string& baseUrl) {
this->m_sBaseUrl = baseUrl;
}
NetworkAdaptor::NetworkAdaptor(const char* baseUrl) {
this->m_sBaseUrl = string(baseUrl);
}
bool NetworkAdaptor::sendValueForKey(const char* key, const char* value, string &wirteBackBuffer) {
map<string, string> content;
content.insert(make_pair(key, value));
sendValueForKey(content, wirteBackBuffer);
return true;
}
bool NetworkAdaptor::sendValueForKey(const map<string, string> &content, string &wirteBackBuffer) {
CURL* curl = curl_easy_init();//初始化curl
if(curl) {
string sendout;
translate(content, sendout);
//配置curl的请求參数
curl_easy_setopt(curl, CURLOPT_URL, m_sBaseUrl.c_str());
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_POST, 1);//post方式
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, sendout.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &wirteBackBuffer); int res = curl_easy_perform(curl);
curl_easy_cleanup(curl); if(res == CURLE_OK) {
CCLog("get data from server : %s", wirteBackBuffer.c_str());
return true;
}else {
CCLog("curl post error");
}
}else {
CCLog("curl init fail");
}
return false;
} void AsynNetworkAdaptor::sendValueForKeyToUrl(const char* key, const char* value, const string &url, string &wirteBackBuffer) {
map<string, string> content;
content.insert(make_pair(key, value));
sendValueForKeyToUrl(content, url, wirteBackBuffer);
}
void AsynNetworkAdaptor::sendValueForKeyToUrl(const map<string, string> content, const string &url, string &wirteBackBuffer) {
RequestInfo info(content, url, wirteBackBuffer);
requests.push_back(info);//将请求放到请求容器中
}
void AsynNetworkAdaptor::flushSendRequests() {
CURLM* curlm = curl_multi_init();
if(curlm) {
for(unsigned int i = 0; i < requests.size(); ++i) {//将请求容器中的请求批量发送到服务端
CURL* curl = curl_easy_init();
if(curl) {
string sendout;
translate(requests[i].content, sendout);
curl_easy_setopt(curl, CURLOPT_URL, requests[i].url.c_str());
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, sendout.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &requests[i].buffer);
int res = curl_easy_perform(curl); curl_multi_add_handle(curlm, curl);
curl_easy_cleanup(curl); }else {
CCLog("curl init fail");
break;
}
} CURLMcode curlm_code = CURLM_CALL_MULTI_PERFORM;
while(CURLM_CALL_MULTI_PERFORM == curlm_code) {
curlm_code = curl_multi_perform(curlm, &m_iUnfinishedRequest);
}
if (curlm_code != CURLM_OK) {
CCLog("curlm post error"); }
curl_multi_cleanup(curlm);
}else {
CCLog("curlm init fail");
}
}

最后写一个測试用例:

	NetworkAdaptor n("http://localhost:8080/TestServlet/TestServlet");
string v;
map<string, string> m;
m.insert(make_pair("name", "myName"));
m.insert(make_pair("password", "myPassword"));
n.sendValueForKey(m, v);
CCLog("%s", v.c_str());

改动server端的代码。使其不跳转。并给client响应一句话

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//request.setAttribute("testt", "test");
//request.getRequestDispatcher("index.jsp").forward(request, response);
String name = request.getParameter("name");
String password = request.getParameter("password");
System.out.println("name: " + name + " , password: " + password);//输出从client发送过来的内容 response.getWriter().print("server have get data");//给client响应一句话
}

如在控制台看到下面測试结果。则表明訪问成功:

服务端:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQva2luZ2FiY2Rl/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">

client:

curl的封装的更多相关文章

  1. curl操作封装

    <?php /** * Class Curl curl简单封装 get post */ class Curl { /** * @brief get请求 * @param $url 请求的url ...

  2. curl简单封装 get post

    Curl.php <?php /** * Class Curl curl简单封装 get post */ class Curl { /** * @brief get请求 * @param $ur ...

  3. php curl 请求封装

    /** * curl 封装函数 * @param string $url 请求地址 * @param string $data 请求数据 * @param string $type 请求方式 默认为G ...

  4. curl类封装

    <?php /**   * @author askwei **/   class CURL   {      private $ch;      private $url = "htt ...

  5. PHP 之CURL请求封装GET、POST、PUT、DELETE

    /** * @Description: curl请求 * @Author: Yang * @param $url * @param null $data * @param string $method ...

  6. 【转】重新封装FetchUrl函数一枚,支持COOKIES,喜欢领走~!

    mjj520 发表于 2012-6-2 09:14 唉 cpu超级耗芸豆的 查了下开发文档,fetchurl原来是不算CPU的,是我误导了大家.  发表于 2012-6-1 17:30:17 |只看该 ...

  7. file_get_contents无法请求https连接的解决方法 php开启curl

    file_get_contents无法请求https连接的解决方法 方法1: PHP.ini默认配置下,用file_get_contents读取https的链接,就会如下错误: Warning: fo ...

  8. [原创]cocos2dx加载网络图片&异步加载图片

    [动机] 之前看到一款卡牌游戏,当你要看全屏高清卡牌的时候,游戏会单独从网络上下载,本地只存了非高清的,这样可以省点包大小,所以我萌生了实现一个读取网络图片的类. [联想] 之前浏览网页的时候经常看到 ...

  9. PHP ElasticSearch的使用

    系统是Windows server 2003. ElasticSearch是一个基于Lucene的稳定的.分布式.RESTFul的搜索引擎.其实所谓的RestFul就是它提供URL供你调用(建立索引和 ...

随机推荐

  1. Axure自动备份功能!让意外不在可怕!

    忘记保存了......... 电脑意外重启了............... 不小心删除了.......................... 每次做axure的时候,多有了太多的意外了! 萧何今天在微 ...

  2. boost::asio async_write也不能保证一次发完所有数据 一

    你要是看过basic_stream_socket的文档,里面提到async_write_some不能保证将所有要发送的数据都发出去.并且提到如果想这样做,需要使用boost asio的async_wr ...

  3. Servlet的学习之web路径问题

    在这个篇章中,我们来学习下在web开发过程中会碰到的路径写法问题. 在之前的web应用开发,尤其是Servlet的学习过程中,我们碰到多次要写路径的问题,这些路径并不统一,因此这里将大致说明下各个方法 ...

  4. HotelIInventory项目小结

    最近参与了HotelIInventory这个项目的一个模块的开发.经验不足,对Sql脚本的编写能力还需要提高,这个模块的Sql语句大多是组长替我写的,如果靠我自己来写,我绝对是没有能力完成工作的,在此 ...

  5. GetCursorPos/WindowFromPoint/SendMessage

    GetCursorPos/WindowFromPoint/SendMessage (用API函数向Edit框发送字符) GetCursorPos(mPoint); DTWND:=WindowFromP ...

  6. 查看内存数据的函数(ByteToHex和ByteToBin,最终都变成String)

    unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms ...

  7. 阿斯钢iojeg9uhweu9erhpu9hyw49

    http://www.huihui.cn/share/8424421 http://www.huihui.cn/share/8424375 http://www.huihui.cn/share/842 ...

  8. Android网络电话软件Sipdroid试用

    Android网络电话软件Sipdroid试用 SipDroid v3.4beta 简介:sipdroid是一款基于网络的语音及视频通话客户端软件,sipdroid本身不经营网络语音服务,仅仅是一款开 ...

  9. KDB支持单步调试功能(ARM架构)

    0    实践发现KDB不支持step调试功能 (本文针对的是arm CotexA9架构,各种架构的实现方式不一样,    X86的好像已经支持,不过本人没有验证过) 1    首先看下要调试的代码段 ...

  10. HDU 2152 Fruit (母函数)

    # include<stdio.h> # include <algorithm> # include <string.h> # include <iostre ...