The package of Curl

Source: Internet
Author: User

First of all to build a httpserver, here used Tomcat6 for example:

Procedure: Create a new servlet and use Tomcat's default port number 8080 to listen, and finally write a JSP to test if you can access the server

1) Create a new Serlvet

Add the test code after the new completion:

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);}}
The name of the servlet is Testservlet. So change the contents of Web. XML to the following

<?

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>

Then write a JSP that will jump after the servlet (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" >
Finally, start the server. In the browser, enter the following address: Http://localhost:8080/TestServlet/TestServlet, you can see the success of the interview



Next in the Cocos2d-x Project Package curl (Cocos2d-x Advanced development tutorial, and added to be able to transfer multiple key-value pairs), the code is relatively simple, directly in the gaze description:

Header file:

A single-threaded send will clog class NetworkAdaptor {public:networkadaptor (const string &baseurl);//construct NetworkAdaptor (const char* BASEURL);//construct bool Sendvalueforkey (const char* key, const char* value, string &wirtebackbuffer);//Send an HTTP request bool Sendvalueforkey (const map<string, string> &content, String &wirtebackbuffer);//Send an HTTP request private: String m_sbaseurl;//The URL address of the request};//a multithreaded thread to send class Asynnetworkadaptor {public:void sendvalueforkeytourl (const char* Key, Const char* Value, const string &url, String &wirtebackbuffer);//Add an HTTP request void Sendvalueforkeytourl (const map& Lt;string, string> content, const string &url, String &wirtebackbuffer);//Add an HTTP request void Flushsendrequests ( )///Bulk Send HTTP request cc_synthesize_readonly (int, m_iunfinishedrequest, unfinishedrequest);//number of sent Protected:struct Requestinfo {//Request information Requestinfo (const map<string, string> &content, const string &url, String &buffer) : Content (content), url (URL), buffer (buffer) {}map<string, string> content;//send content string url;//request URL address string &buffer;//server callback content};vector<requestinfo> requests;//request container}; 
CPP file:

Converts the contents of a key-value pair into a form-formatted content for transfer 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-&G T;first + "=" + It->second) + "&";} Sendout = sendout.substr (0, Sendout.length ()-1);//Remove the last & character}//callback function. Be sure to return the server corresponding to the byte size 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 ();//Initialize Curlif (CURL) { String sendout;translate (content, sendout);//Configuration Curl Request parameter 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 mode 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 &wirt Ebackbuffer) {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);//Place the request in the request container}void Asynnetworkadaptor::flushsendrequests () {curlm* CURLM = Curl_multi_init (), if (CURLM) {for (unsigned int i = 0; i < reques Ts.size (); ++i) {//The request in the request container is sent in bulk to the server 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"); 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");}}

Finally write a test example:

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 ());
Change the server-side code. So that it does not jump. and respond to a word to the 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);//outputs the content sent from the client Response.getwriter (). Print ("server hav E get Data ");//respond to a word to the client}
See the following test results in the console. Indicates a successful interview:

Service side:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqva2luz2fiy2rl/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">

Client




The package of Curl

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.