热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

ballerina学习二十http/https

提供http&&httpsserver&&client访问功能clientendpoint说白了就是httpclient参考

提供http && https server && client 访问功能

client endpoint

说白了就是http client

  • 参考代码
import ballerina/http;
import ballerina/log;endpoint http:Client clientEndpoint {
    url: "https://postman-echo.com"
};function main(string... args) { http:Request req = new;
    var respOnse= clientEndpoint->get("/get?test=123"); match response {
        http:Response resp => {
            log:printInfo("GET request:");
            var msg = resp.getJsonPayload();
            match msg {
                json jsOnPayload=> {
                    log:printInfo(jsonPayload.toString());
                }
                error err => {
                    log:printError(err.message, err = err);
                }
            }
        }
        error err => { log:printError(err.message, err = err); }
    }
    req.setPayload("POST: Hello World"); respOnse= clientEndpoint->post("/post", request = req);
    match response {
        http:Response resp => {
            log:printInfo("\nPOST request:");
            var msg = resp.getJsonPayload();
            match msg {
                json jsOnPayload=> {
                    log:printInfo(jsonPayload.toString());
                }
                error err => {
                    log:printError(err.message, err = err);
                }
            }
        }
        error err => { log:printError(err.message, err = err); } }
    json jsOnMsg= { method: "PUT", payload: "Hello World" };
    req.setJsonPayload(jsonMsg); respOnse= clientEndpoint->put("/put", request = req);
    match response {
        http:Response resp => {
            log:printInfo("\nPUT request:");
            var msg = resp.getJsonPayload();
            match msg {
                json jsOnPayload=> {
                    log:printInfo(jsonPayload.toString());
                }
                error err => {
                    log:printError(err.message, err = err);
                }
            }
        }
        error err => { log:printError(err.message, err = err); }
    }
    xml xmlMsg = xml `
                        PATCH
                        Hello World!
                      `;
    req.setXmlPayload(xmlMsg); respOnse= clientEndpoint->patch("/patch", request = req);
    match response {
        http:Response resp => {
            log:printInfo("\nPATCH request:");
            var msg = resp.getJsonPayload();
            match msg {
                json jsOnPayload=> {
                    log:printInfo(jsonPayload.toString());
                }
                error err => {
                    log:printError(err.message, err = err);
                }
            }
        }
        error err => { log:printError(err.message, err = err); }
    } req.setPayload("DELETE: Hello World");
    respOnse= clientEndpoint->delete("/delete", request = req);
    match response {
        http:Response resp => {
            log:printInfo("\nDELETE request:");
            var msg = resp.getJsonPayload();
            match msg {
                json jsOnPayload=> {
                    log:printInfo(jsonPayload.toString());
                }
                error err => {
                    log:printError(err.message, err = err);
                }
            }
        }
        error err => { log:printError(err.message, err = err); }
    } req.setPayload("CUSTOM: Hello World");
    respOnse= clientEndpoint->execute("COPY", "/get", req); req = new;
    req.addHeader("Sample-Name", "http-client-connector");
    respOnse= clientEndpoint->get("/get", request = req);
    match response {
        http:Response resp => {
            string cOntentType= resp.getHeader("Content-Type");
            log:printInfo("\nContent-Type: " + contentType); int statusCode = resp.statusCode;
            log:printInfo("Status code: " + statusCode); }
        error err => { log:printError(err.message, err = err); }
    }
}
  • 输出结果
2018-06-01 21:03:32,032 INFO [] - GET request:
2018-06-01 21:03:32,059 INFO [] - {"args":{"test":"123"},"headers":{"host":"postman-echo.com","user-agent":"ballerina/0.970.1","x-forwarded-port":"443","x-forwarded-proto":"https"},"url":"https://postman-echo.com/get?test=123"}
2018-06-01 21:03:32,633 INFO [] -
POST request:
2018-06-01 21:03:32,636 INFO [] - {"args":{},"data":"POST: Hello World","files":{},"form":{},"headers":{"host":"postman-echo.com","content-length":"17","content-type":"text/plain","user-agent":"ballerina/0.970.1","x-forwarded-port":"443","x-forwarded-proto":"https"},"json":null,"url":"https://postman-echo.com/post"}
2018-06-01 21:03:33,349 INFO [] -
PUT request:
2018-06-01 21:03:33,351 INFO [] - {"args":{},"data":{"method":"PUT","payload":"Hello World"},"files":{},"form":{},"headers":{"host":"postman-echo.com","content-length":"40","content-type":"application/json","user-agent":"ballerina/0.970.1","x-forwarded-port":"443","x-forwarded-proto":"https"},"json":{"method":"PUT","payload":"Hello World"},"url":"https://postman-echo.com/put"}
2018-06-01 21:03:33,861 INFO [] -
PATCH request:
2018-06-01 21:03:33,863 INFO [] - {"args":{},"data":"\n PATCH<\/method>\n Hello World!<\/payload>\n <\/request>","files":{},"form":{},"headers":{"host":"postman-echo.com","content-length":"145","content-type":"application/xml","user-agent":"ballerina/0.970.1","x-forwarded-port":"443","x-forwarded-proto":"https"},"json":null,"url":"https://postman-echo.com/patch"}
2018-06-01 21:03:34,373 INFO [] -
DELETE request:
2018-06-01 21:03:34,375 INFO [] - {"args":{},"data":"DELETE: Hello World","files":{},"form":{},"headers":{"host":"postman-echo.com","content-length":"19","content-type":"text/plain","user-agent":"ballerina/0.970.1","x-forwarded-port":"443","x-forwarded-proto":"https"},"json":null,"url":"https://postman-echo.com/delete"}
2018-06-01 21:03:35,193 INFO [] -
Content-Type: application/json; charset=utf-8
2018-06-01 21:03:35,193 INFO [] - Status code: 200

http client redirect

redirect 是服务器端的相应,一般http 客户端不会进行处理,ballerina 有可选的配置参数,同时可以设置最大次数(防止死循环)

  • 参考代码
import ballerina/io;
import ballerina/http;
import ballerina/log;
import ballerina/mime;endpoint http:Client clientEP {
    url: "http://localhost:9090",
    followRedirects: { enabled: true, maxCount: 5 }
};
function main(string... args) {
    var returnResult = clientEP->get("/redirect1");

    match returnResult {
        error cOnnectionErr=> log:printError("Error in connection",
            err = connectionErr);
        http:Response resp => {
            match resp.getTextPayload() {
                error e => log:printError("Error in payload", err = e);
                string payload => io:println("Response received : " + payload);
            }
        }
    }
}
@http:ServiceConfig {
    basePath:"/redirect1"
}
service redirect1 bind {port:9090} { @http:ResourceConfig {
        methods:["GET"],
        path:"/"
    }
    redirect1 (endpoint client, http:Request req) {
        http:Response res = new;
        _ = client -> redirect(res, http:REDIRECT_TEMPORARY_REDIRECT_307,
            ["http://localhost:9093/redirect2"]);
    }
}@http:ServiceConfig {
    basePath:"/redirect2"
}
service redirect2 bind {port:9093} { @http:ResourceConfig {
        methods:["GET"],
        path:"/"
    }
    redirect2 (endpoint client, http:Request req) {
        http:Response res = new;
        res. setPayload("Hello World!");
        _ = client -> respond( res) but { error e => log:printError("Error in
        responding", err = e) };
    }
}

## http server base path && params

  • 参考代码
import ballerina/http;
import ballerina/log;
import ballerina/mime;
@http:ServiceConfig { basePath: "/foo" }
service echo bind { port: 9090 } {
    @http:ResourceConfig {
        methods: ["POST"],
        path: "/bar"
    }
    echo(endpoint caller, http:Request req) {
        var result = req.getJsonPayload();
        http:Response res = new;
        match result {
            error err => {
                res.statusCode = 500;
                res.setPayload(err.message);
            }
            json value => {
                res.setJsonPayload(value);
            }
        }
        caller->respond(res) but {
            error e => log:printError("Error in responding", err = e)
        };
    }
}

import ballerina/http;
import ballerina/log;@http:ServiceConfig
service sample bind { port: 9090 } { @http:ResourceConfig {
        methods: ["GET"],
        path: "/path/{foo}"
    }
    params(endpoint caller, http:Request req, string foo) {
        var params = req.getQueryParams();
        var bar = params.bar;
        map pathMParams = req.getMatrixParams("/sample/path");
        var a = pathMParams.a;
        var b = pathMParams.b;
        string pathMatrixStr = string `a={{a}}, b={{b}}`;
        map fooMParams = req.getMatrixParams("/sample/path/" + foo);
        var x = fooMParams.x;
        var y = fooMParams.y;
        string fooMatrixStr = string `x={{x}}, y={{y}}`;
        json matrixJson = { "path": pathMatrixStr, "foo": fooMatrixStr };
        json respOnseJson= { "pathParam": foo, "queryParam": bar, "matrix": matrixJson };
        http:Response res = new;
        res.setJsonPayload(responseJson);
        caller->respond(res) but { error e => log:printError("Error when responding", err = e) };
    }
}

https server

  • 参考代码
import ballerina/http;
import ballerina/log;
endpoint http:Listener helloWorldEP {
    port: 9095,
    secureSocket: {
        keyStore: {
            path: "${ballerina.home}/bre/security/ballerinaKeystore.p12",
            password: "ballerina"
        }
    }
};
@http:ServiceConfig {
    basePath: "/hello"
}
service helloWorld bind helloWorldEP {
    @http:ResourceConfig {
        methods: ["GET"],
        path: "/"
    } 
 sayHello(endpoint caller, http:Request req) {
        http:Response res = new;
        res.setPayload("Hello World!");
        caller->respond(res) but {
                    error e => log:printError("Error in responding ", err = e) };
    }
}

cors

一般进行跨域处理

  • 参考代码
import ballerina/http;
import ballerina/log;
@http:ServiceConfig {
    cors: {
        allowOrigins: ["http://www.m3.com", "http://www.hello.com"],
        allowCredentials: false,
        allowHeaders: ["CORELATION_ID"],
        exposeHeaders: ["X-CUSTOM-HEADER"],
        maxAge: 84900
    }
}
service crossOriginService bind { port: 9092 } { string respErr = "Failed to respond to the caller";
    @http:ResourceConfig {
        methods: ["GET"],
        path: "/company",
        cors: {
            allowOrigins: ["http://www.bbc.com"],
            allowCredentials: true,
            allowHeaders: ["X-Content-Type-Options", "X-PINGOTHER"]
        }
    }
    companyInfo(endpoint caller, http:Request req) {
        http:Response res = new;
        json respOnseJson= { "type": "middleware" };
        res.setJsonPayload(responseJson);
        caller->respond(res) but { error e => log:printError(respErr, err = e) };
    }
    @http:ResourceConfig {
        methods: ["POST"],
        path: "/lang"
    }
    langInfo(endpoint caller, http:Request req) {
        http:Response res = new;
        json respOnseJson= { "lang": "Ballerina" };
        res.setJsonPayload(responseJson);
        caller->respond(res) but { error e => log:printError(respErr, err = e) };
    }
}

数据绑定

http body 序列化

  • 参考代码
import ballerina/http;
import ballerina/io;
import ballerina/log;type Student {
    string Name;
    int Grade;
    map Marks;
};
@http:ServiceConfig
service hello bind { port: 9090 } { string respErr = "Failed to respond to the caller";
    @http:ResourceConfig {
        methods: ["POST"],
        body: "orderDetails"
    }
    bindJson(endpoint caller, http:Request req, json orderDetails) {
        json details = orderDetails.Details; http:Response res = new;
        res.setPayload(details);
        caller->respond(res) but { error e => log:printError(respErr, err = e) };
    }
    @http:ResourceConfig {
        methods: ["POST"],
        body: "store",
        consumes: ["application/xml"]
    }
    bindXML(endpoint caller, http:Request req, xml store) {
        xml city = store.selectDescendants("{http://www.test.com}city"); http:Response res = new;
        res.setPayload(city);
        caller->respond(res) but { error e => log:printError(respErr, err = e) };
    }
    @http:ResourceConfig {
        methods: ["POST"],
        body: "student",
        consumes: ["application/json"]
    }
    bindStruct(endpoint caller, http:Request req, Student student) {
        string name = student.Name; int grade = student.Grade; http:Response res = new;
        res.setPayload({ Name: name, Grade: grade });
        caller->respond(res) but { error e => log:printError(respErr, err = e) };
    }
}

参考资料

https://ballerina.io/learn/by-example/http-client-endpoint.html
https://ballerina.io/learn/by-example/https-listener.html
https://ballerina.io/learn/by-example/http-cors.html
https://ballerina.io/learn/by-example/http-data-binding.html

 
 
 
 

推荐阅读
  • 个人学习使用:谨慎参考1Client类importcom.thoughtworks.gauge.Step;importcom.thoughtworks.gauge.T ... [详细]
  • 关键词:Golang, Cookie, 跟踪位置, net/http/cookiejar, package main, golang.org/x/net/publicsuffix, io/ioutil, log, net/http, net/http/cookiejar ... [详细]
  • 网络请求模块选择——axios框架的基本使用和封装
    本文介绍了选择网络请求模块axios的原因,以及axios框架的基本使用和封装方法。包括发送并发请求的演示,全局配置的设置,创建axios实例的方法,拦截器的使用,以及如何封装和请求响应劫持等内容。 ... [详细]
  • Spring源码解密之默认标签的解析方式分析
    本文分析了Spring源码解密中默认标签的解析方式。通过对命名空间的判断,区分默认命名空间和自定义命名空间,并采用不同的解析方式。其中,bean标签的解析最为复杂和重要。 ... [详细]
  • 本文介绍了使用AJAX的POST请求实现数据修改功能的方法。通过ajax-post技术,可以实现在输入某个id后,通过ajax技术调用post.jsp修改具有该id记录的姓名的值。文章还提到了AJAX的概念和作用,以及使用async参数和open()方法的注意事项。同时强调了不推荐使用async=false的情况,并解释了JavaScript等待服务器响应的机制。 ... [详细]
  • http:my.oschina.netleejun2005blog136820刚看到群里又有同学在说HTTP协议下的Get请求参数长度是有大小限制的,最大不能超过XX ... [详细]
  • 在重复造轮子的情况下用ProxyServlet反向代理来减少工作量
    像不少公司内部不同团队都会自己研发自己工具产品,当各个产品逐渐成熟,到达了一定的发展瓶颈,同时每个产品都有着自己的入口,用户 ... [详细]
  • [大整数乘法] java代码实现
    本文介绍了使用java代码实现大整数乘法的过程,同时也涉及到大整数加法和大整数减法的计算方法。通过分治算法来提高计算效率,并对算法的时间复杂度进行了研究。详细代码实现请参考文章链接。 ... [详细]
  • 本文介绍了南邮ctf-web的writeup,包括签到题和md5 collision。在CTF比赛和渗透测试中,可以通过查看源代码、代码注释、页面隐藏元素、超链接和HTTP响应头部来寻找flag或提示信息。利用PHP弱类型,可以发现md5('QNKCDZO')='0e830400451993494058024219903391'和md5('240610708')='0e462097431906509019562988736854'。 ... [详细]
  • 本文介绍了django中视图函数的使用方法,包括如何接收Web请求并返回Web响应,以及如何处理GET请求和POST请求。同时还介绍了urls.py和views.py文件的配置方式。 ... [详细]
  • Python SQLAlchemy库的使用方法详解
    本文详细介绍了Python中使用SQLAlchemy库的方法。首先对SQLAlchemy进行了简介,包括其定义、适用的数据库类型等。然后讨论了SQLAlchemy提供的两种主要使用模式,即SQL表达式语言和ORM。针对不同的需求,给出了选择哪种模式的建议。最后,介绍了连接数据库的方法,包括创建SQLAlchemy引擎和执行SQL语句的接口。 ... [详细]
  • Imtryingtofigureoutawaytogeneratetorrentfilesfromabucket,usingtheAWSSDKforGo.我正 ... [详细]
  • 解决nginx启动报错epoll_wait() reported that client prematurely closed connection的方法
    本文介绍了解决nginx启动报错epoll_wait() reported that client prematurely closed connection的方法,包括检查location配置是否正确、pass_proxy是否需要加“/”等。同时,还介绍了修改nginx的error.log日志级别为debug,以便查看详细日志信息。 ... [详细]
  • 本文讨论了如何在codeigniter中识别来自angularjs的请求,并提供了两种方法的代码示例。作者尝试了$this->input->is_ajax_request()和自定义函数is_ajax(),但都没有成功。最后,作者展示了一个ajax请求的示例代码。 ... [详细]
  • Spring常用注解(绝对经典),全靠这份Java知识点PDF大全
    本文介绍了Spring常用注解和注入bean的注解,包括@Bean、@Autowired、@Inject等,同时提供了一个Java知识点PDF大全的资源链接。其中详细介绍了ColorFactoryBean的使用,以及@Autowired和@Inject的区别和用法。此外,还提到了@Required属性的配置和使用。 ... [详细]
author-avatar
平凡无琦世界
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有