#ApiDoc
Explore tagged Tumblr posts
writedocs111 · 3 months ago
Text
API documentation Made Simple | API Blogger
Struggling with API docs? Keep it clear, concise, and developer-friendly! Use: 📌 Real-world examples – Show how it works 📌 Consistent structure – Endpoints, methods, and responses 📌 Interactive tools – Postman collections & Swagger UI 📌 Error handling – Explain responses & solutions
The goal? Faster integration, fewer support tickets! #APIDocs #DeveloperExperience #TechSimplified
0 notes
whiskeychocokeopi-blog · 3 years ago
Link
Shout out to Giorgos Myrianthous for his article on Medium. I found his article helpful. Spot on to fix the issue. Thank you.  
2 notes · View notes
loveayase · 5 years ago
Text
Python - IBM Watson TTS API
1. 개요
평소에 유튜브 보다 트위치 방송을 자주보는 편인데... 도네이션을 보면 굉장히 머리를 탁! 치게 하는 엄청난 드립들이 많이 보였다. TTS 서비스가 최초에는 남자 여자 정도밖에 없었는데, 어느새 잼민이도 나오고 기타 등등도 나오는 것으로 봥서 저거 녹음을 직접 다하는 건지.. 아니면 최근에 GAN 기반의 인공���능 모델에 목소리를 합성해서 만든건지 궁금했다.
그리고 가장 알고싶었던건 도네이션 과연 원가가 얼마인가 싶었다. 알아보니 아니나다를까 모델자체를 학습하고, 데이터가 많이 수집되어있는 곳은 구글, IBM 같은 기업이었고 구글 TTS를 사용하려다가 구글은 메뉴얼도 아주 잘되어있고 성능도 좋을 것 같고, 혹시 내가 업무에서 사용할지도 모르니까 크레딧을 아끼자는 측면에서 IBM Watson TTS를 적용해보았다.
트위치 방송에 사용되는 프로그램은 OBS Studio가 대표적인데 도네이션을 연동한다는 의미는 아래와 같다
OBS Studio의 웹페이지를 연동, 해당 웹페이지의 javascript, css 등의 코드를 통하여 구현, 일반적으로 웹페이지는 이벤트기반의 동작이기 때문에 서버로부터 이벤트를 받아서 처리하기 위해서 socket.io 연동까지가 프론트엔드 사이드
socket.io 메시지를 보내기 위한 백엔드 사이드, 및 이벤트 발생
딱 보니 저렇게 구현하면 되겠다 싶어서 직접 만들어 보았다. 아 여기서 본인이 사업화를 하고 싶다면 도네이션을 받는 사이트를 만들면되겠다. 필자는 웹프로그래밍에 지쳐 더이상은 Naver를 외치면서, 트위치 챗봇을 연동했다. 
2. 도전 해본 새로운 기술
IBM Watson TTS Service
TTS는 Text to Speech로써, 문장을 보고 사람이 읽는 듯한 음성을 만들어내는 서비스를 말한다.
ibm의 경우 한달에 10,000글자까지는 무료로 제공하고 있으며, 유료의 경우에는 한달에 1000글자당 0.02$를 청구한다.
트위치 챗봇
트위치의 채팅시스템은 20년전의 IRC시스템을 공유하고 있다. 따라서 IRC를 조금 해본 사람들이면 아 이게 비슷한데 라는 느낌을 많이 받을 것이며, 안 받는다면 트위치 채팅을 굉장히 커스터마이징 했기 때문이라고 생각하면된다.
3. 까먹지 않기 위해 복습한 기술
는 따로 없습니다 ㅎ
4. 결과
영상편집 중
References
IBM Watson  https://cloud.ibm.com/apidocs/text-to-speech
0 notes
giriton-en · 5 years ago
Text
REST api to work with Shifts
With REST api you can newly read, add and edit the shifts. In addition, you can read and edit shift schedules as well as register user to shifts. Connection to other in-house systems is thus much easier. REST api documentation is here: https://rest.giriton.com/apidoc/
0 notes
simplythetest · 6 years ago
Text
Pytest, The Awesome Parts: Requests
In my final post about how awesome Pytest is, I'd like to bend the rules a bit and talk about how awesome another excellent Python library is: requests. Requests is hands down one of my favourite pieces of software. Just like it says at the top of its home page, requests is HTTP made for humans.
Let's look for an example with the handy Restful-Booker app by Mark Winteringham:
import requests r = requests.get('https://restful-booker.herokuapp.com/booking') print(r.status_code) # should be 200 print(r.text) # response body, should look like [{"bookingid":3},{"bookingid":1},... print(r.json()) # same as r.text but in valid JSON
Straightforward and easy. No malarkey here, just HTTP requests and responses.
Requests is nice because of its syntax and because it is a full featured HTTP library. Whether you need a one time simple GET or a more complicated request requiring things like manipulating headers or authentication along with a custom request body, requests has you covered.
Tying this back into Pytest and test automation, two questions I've seen a lot of teams and developers have are
"How do I build an API test framework?", and
"How can I use APIs in my automated browser tests for more stability?"
One (good) answer to both is "build your own with Pytest and Requests".
For an example of API tests, a typical case is to examine the status code of a response. With requests, this is pretty easy. Here is what some basic GET style tests look like:
import pytest import requests def test_app_is_available(): response = requests.get("https://restful-booker.herokuapp.com/booking") assert response.ok def test_page_unavailable(): response = requests.get("https://restful-booker.herokuapp.com/not_there.html") assert response.status_code == 404
These tests verify if web app under test is up, meaning returning a 200- or 300-level HTTP status, and if a particular page does not exist and returns the correct 404 status. (For a fun reference on HTTP statuses and what they mean, please see http.cat.) In each case the .get() method returns a Response that can be used in a variety of ways. The first test makes use of requests' Response.ok property. The second test looks for the particular status code of 404. While these tests are fairly elementary, they do represent core kinds of API tests: making a request and analyzing the response. Requests and Pytest make a great combination to start simple and build up tests as needed.
Another really great feature of requests for automated testing is the Requests Session construct. This allows for handling of a series of HTTP requests, maintaining stateful aspects of a session such as authentication, cookies, and so on.
Here requests can help with building API utilities for browser testing. Here's a possible test that uses an API request directly to login to a web app instead of using the app UI:
import pytest import requests from selenium import webdriver @pytest.fixture def logged_in_browser(request): api_session = requests.session.post("https://my-web-app.net/login", auth=('myuser', 'mypass')) cookies = api_session.cookies cookie = cookies['needed_cookie_from_authentication'] driver = webdriver.Firefox() driver.add_cookie(cookie) yield driver driver.quit() api.session.close() def create_entry_test(logged_in_browser): driver.get("https://my-web-app.net/welcome_page.html") # fast forward to the desired page # continue with the test
Again, straightforward and clean. It is even possible to separate the API and browser sessions into different fixtures so that API- and browser-driven actions in a set of automated tests.
I've had success using the requests session in exactly these ways. For an example of an API test framework based on requests, take a look at svp.
In conclusion, Python's requests is incredible. Requests is almost a good enough reason to learn Python for testers and SDETs.
0 notes
webdevq-com · 6 years ago
Text
Скрипт по смене паролей на почтовых сервисах • Фриланс-проект ≡ Заказчик Денис Чуприна
New Post has been published on https://ru.webdevq.com/project/skript-po-smene-parolei-na-pochtovyh-servisah-frilans-proekt-zakazchik-denis-chyprina/
Скрипт по смене паролей на почтовых сервисах • Фриланс-проект ≡ Заказчик Денис Чуприна
Необходимо сделать скрипт для смены пароля почты для разных почтовых сервисов, например: aol*com, seznam*cz, rediffmail*com, yahoo*com, yandex*ru (их 5) в перспективе еще будет около 50 (отдельная оплата)
с прохождением recapcha (модуль есть в отрытом доступе рекапчи — anti-captcha.com/apidoc/image ).
Этот скрипт должен исполняться на компьютере (windows) на определенном порту — принимать строку запроса и выдавать результат (ошибка при смене — или новый пароль для почты)
ЛЮБОЙ ПОДХОДЯЩИЙ ЯЗЫК ПРОГРАММИРОВАНИЯ.
Источник
0 notes
yes-husky · 6 years ago
Text
Скрипт по смене паролей на почтовых сервисах • Фриланс-проект ≡ Заказчик Денис Чуприна
New Post has been published on https://ru.webdevq.com/project/skript-po-smene-parolei-na-pochtovyh-servisah-frilans-proekt-zakazchik-denis-chyprina/
Скрипт по смене паролей на почтовых сервисах • Фриланс-проект ≡ Заказчик Денис Чуприна
Необходимо сделать скрипт для смены пароля почты для разных почтовых сервисов, например: aol*com, seznam*cz, rediffmail*com, yahoo*com, yandex*ru (их 5) в перспективе еще будет около 50 (отдельная оплата)
с прохождением recapcha (модуль есть в отрытом доступе рекапчи — anti-captcha.com/apidoc/image ).
Этот скрипт должен исполняться на компьютере (windows) на определенном порту — принимать строку запроса и выдавать результат (ошибка при смене — или новый пароль для почты)
ЛЮБОЙ ПОДХОДЯЩИЙ ЯЗЫК ПРОГРАММИРО��АНИЯ.
Источник
0 notes
tippytopshapeusa · 7 years ago
Photo
Tumblr media
#Please_share #tgif #hpp1778 #hpp #1778 20181019 1222PM * ~ #L hpp 1778 - Google Search https://www.google.com/search?q=hpp+1778&oq=hpp+1778&aqs=chrome..69i57.4235j0j4&client=ms-android-boost-us&sourceid=chrome-mobile&ie=UTF-8 Modern Nutrition in Health and Disease - Google Books https://books.google.com/books?id=S5oCjZZZ1ggC&pg=PA1777&lpg=PA1777&dq=hpp+1778&source=bl&ots=2yKJz_lHwC&sig=8Q9N6WsTH2dSrVd6SL6mqqTQ09M&hl=en&sa=X&ved=2ahUKEwir6sGx8pLeAhUnWN8KHbl-C-Q4ChDoATADegQICBAB#v=onepage&q=hpp%201778&f=false Xerces-C++: AbstractDOMParser.hpp Source File https://xerces.apache.org/xerces-c/apiDocs-3/AbstractDOMParser_8hpp_source.html hpp1778 - Google Search https://www.google.com/search?client=ms-android-boost-us&ei=HenJW9TtPOKI_QbK5ICICg&ins=false&q=hpp1778&oq=hpp1778&gs_l=mobile-gws-wiz-serp.3...12225.12225..13461...0.0..0.235.235.2-1......0....1.NstvURFdChQ 1778 hpp - Google Search https://www.google.com/search?client=ms-android-boost-us&ei=-ALKW7q-FrCb_Qb-mYGoDQ&ins=false&q=1778+hpp&oq=1778+hpp&gs_l=mobile-gws-wiz-serp.3...20605.21708..22981...0.0..0.103.181.1j1......0....1.xvaNUUpyM3M 1778hpp - Google Search https://www.google.com/search?client=ms-android-boost-us&ei=YQPKW5z0N-TI_QbFobzwCw&ins=false&q=1778hpp&oq=1778hpp&gs_l=mobile-gws-wiz-serp.3..35i304i39.52684.52684..53203...0.0..0.112.112.0j1......0....1.pefkmK98wSE https://www.instagram.com/p/BpHwm3YH-sk/?utm_source=ig_tumblr_share&igshid=an9hj0auwjep
0 notes
giriton-cz · 5 years ago
Text
REST api pro práci se směnami
Pomocí REST api můžete nově číst i upravovat směny z číselníku směn. Navíc můžete číst i upravovat plány směn a také registraci směn uživatelů. Napojení na další vnitropodnikové systémy je tak mnohem jednodušší. Dokumentaci REST api naleznete zde: https://rest.giriton.com/apidoc/
0 notes
apecode-blog · 7 years ago
Text
日志级别如何划分?
日志记录是软件开发的一个概念,几乎所有(可能并不是所有)软件都能从日志记录中获得很多好处。在开始一个大项目时,日志记录通常是我第一个要搭建的子系统。关于它的好处,我可以说出一大堆,但我想把这个机会留给其他人(或者哪一天我想说了再说)。现在,我想说一说日志级别。
日志级别是对基本的“滚动文本”式日志记录的一个重要补充。每条日志消息都会基于其重要性或严重程度分配到一个日志级别。例如,“你的电脑着火了”是一个非常重要的消息,而“无法找到配置文件”的重要等级可能就低一些。
很多应用程序和库会根据自己或用户的需求定义自己的日志级别(参考文末的“外部例子”了解这方面的内容)。当然,并没有一种约定俗成的方法来做这件事,想怎么做都是可以的,但我想要说说我认为的最重要的五个(或者六个,或者四个)日志级别,它们应该是你自定义日志级别的基础。
我还将讨论给这些级别分配的颜色(或者说风格),因为带有不同颜色(或风格)的日志更容易追踪。如果采用了这样的系统,就可以很容易检查你的程序状态,就算没有受过训练的人也可以轻易分辨。谁知道呢,你可能留下电脑跑去吃午饭了,如果出现问题只能找别人来查看日志。
E r r o r  
错误已经发生了,这是毫无疑问的。错误的来源可能是在外部,但不管怎样都需要看一下是怎么回事。
可以用这个级别来表示需要引起人们注意(大多数时候需要采取行动)的错误。大多数难以优雅处理的异常都属于 Error 范畴。
风格:能引起人们注意的东西。我使用红色文本来表示(我的终端背景是黑色的)。 例子: * 无法找到"crucial.dat"文件 * 错误的处理数据:[堆栈追踪或后续的调试消息] * 在连接数据库时 * 在连接数据库时
W a r n
错误有可能已经发生了。我只是一条日志消息,无法分析到底发生了什么,或许需要其他人来看看是不是有问题。
这可能是一个平行空间里的错误。它可能是当前或未来潜在问题(比如响应速度慢、连接断开、内存吃紧等等)的预兆,也可能是程序在处理某些任务时出现错误(但可能不一会再发生类似的情况)。
风格:能引起人们注意但又不会让人感到厌烦的风格,以免你在解决其他问题时没空来处理这些错误。与 Error 的风格不同,我使用黄色的文本来表示 Warn。
例子: * 连接关闭,在 2 秒后重新连接 * 无法找到"logging.conf"[在配置文件中指定的],回到默认配置 * 30 秒后尝试连接超时 * 出现 FileVersionTooOldException 异常,回到 Version12Parser
I n f o
通知用户一个操作或状态发生了变化。别紧张,继续手头的活。
Info 可以说是(一般的非技术)用户可以接触到的最“啰嗦”的日志级别。如果有人把它们大声念给你听,你也不会介意,这是你最乐于见到的日志记录。它不会包含很多技术细节,可能只包含普通用户会关注的信息(比如文件名等)。
风格:可以和背景颜色区分开来,我使用白色文本。
例子: * 代理初始化完毕 * 加载存档"yeti02" * 进入高速模式 * 当前目录是"/tmp" * 上行线路已建立 * 渲染完成,耗时 42.999 秒
Debug
如果你能读懂这个级别的日志,那么你离程序已经很近了。
这就是为什么你需要保存日志文件,在修复 bug 时需要这些日志。这是开发人员最关心的内容。
在转储程序运行流程和其他技术问题时,应该使用 Debug 级别的日志。除非日志太多了(在这种情况下使用 Trace 级别更合适)或者更适合使用更高级别的日志,否则 Debug 日志是非常值得保留的,毕竟是你自己在代码中记录这些日志的。如果和其他的Debug 或更高级别的消息重叠,而且没有包含更多的信息,那么可以考虑将其删除。
风格:可以很容易就忽略的风格。我使用浅灰色或米黄色文本,也就是我的终端的默认文本颜色。
例子: * 从"/etc/octarine/octarine.conf"读取配置 * 使用"/home/aib/.octarinerc"覆盖配置 * 分析完成,创建图… * 作为”user”连接到服务器:4242 * 发送两条消息 * 渲染时故障: * Foo 0.990 秒 * Bar 42.009 秒 
Trace
这些技术细节可能与程序不是很相干,除非你正好需要它们。
Trace 的信息是更加具体的调试信息,你可能并不想看到它(除非你向保存日志的人卖硬盘的时候需要)。它会包含比如说调用了什么函数(函数名),或是和客户端交换了什么网络包等内容。它善于找到一些低级错误,但通常你可以在调试消息中缩小范围,找到问题。
大多数 Trace 消息包含了你已经知道的信息(Debug消息中说了是“登录”,所以这肯定是登录相关的数据包),所以可能对你不是很有用,除非你的假设是错误的。(��它会不会是登出消息?!“、”这里应该调用 foo。为什么 foo 的 Trace 信息没有打印出来呢?”)
风格:使用比 Debug
消息更加不显眼的风格。我使用深灰色,通常用来表示禁用的颜色。 例子:
调用参数 ("baz", "bar", 42) 函数”foo”
->GET / HTTP/1.1\nHost: localhost\n\n
收到: \n\n [...]
F a t a l
发生了一个致命错误,我们要退出了。祝你好运!
它应该比 Error 更严重,但使用它的频率比 Trace 还少,所以我把它放在文章的最后。顾名思义,致命错误表示这种情况的发生将导致程序无法继续运行。因此,给它们专门设置一个级别没什么意义。但是致命的错误也可能是常见和可恢复的(比如重启就能解决),因此仍然值得一提。
风格:如果你想不出其他样式的话,可以选择比 Error 更显眼的风格。我使用紫色文本,从远处看的话和 Error 的红色文本相近,但近看就不一样。
例子: * 内存不足 * 无法分配 65536 字节的磁盘空间 * 许可过期,切换到免费软件模式
外部例子
任何成熟的日志记录 API 或库都应该有自己的日志级别(可能支持用户自定义)。以下是广泛使用的库,仅供参考:
Linux 的 printk * https://en.wikipedia.org/wiki/Printk#Logging_Levels
Python 的 logging * https://docs.python.org/library/logging.html#logging-levels
Java 的java.util.logging.Level https://docs.oracle.com/javase/6/docs/api/java/util/logging/Level.html log4j 的 org.apache.log4j.Level * https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Level.html * JavaScript 的 console.level 调用 WHATWG 或 Node.js 的 Console API 规范
NLog 的日志级别 * https://github.com/nlog/nlog/wiki/Log-levels
0 notes
innovanon-inc · 7 years ago
Text
Status Update: Random Object Instantiator
Tumblr media
Created a more generic query-url supplier. Can support other sites. Uses a randomly-selected subset of optional parameters.
Docs: http://lmaddox.chickenkiller.com/docs/Simon/apidocs/index.html
Sample URL: https://pixabay.com/api/?min_width=91&order=latest&q=interrompere+interromperla+interrompersi&lang=it&key=<my api key>
Sample result: https://pixabay.com/get/ea33b70c2df5023ed1584d05fb1d4796e170e3d018b50c4090f3c971a6efb2bbda_1280.jpg
Source Code: https://github.com/InnovAnon-Inc/PP
0 notes
ungdungmoi · 7 years ago
Text
[Xây dựng WebGIS #8] – Bật tắt layer, hiển thị Legends
Bài này mình sẽ giới thiệu một và chức năng cơ bản của webGIS là bật tắt layer, hiển thị các legend.
Ở code bài trước, chúng ta sẽ thêm các checkbox, mỗi checkbox ứng với 1 layer. Ở đây mình chỉ có một layer nên mình sẽ thêm 1 checkbox như code dưới:
<input type="checkbox" id="chkThuaDat" checked /><label for="chkThuaDat">Thửa đất</label>
Mặc định chúng ta sẽ hiển thị layer này lên nên sẽ để thuộc tính checked ngay từ đầu.
Trong hàm $(“document”).ready(function(){…}); chúng ta sẽ thêm code bắt sự kiện checkbox này check như sau:
$("#chkThuaDat").change(function () { if($("#chkThuaDat").is(":checked")) { ThuaDat.setVisible(true); } else { ThuaDat.setVisible(false); } });
ThuaDat là layer chúng ta đã khai báo bên trên. Hàm setVisible(var) xác định layer hiển thị hay ko. Chú ý là tùy từng phiên bản Openlayer thì tên hàm có thể khác nhau, các bạn có thể check tại đây: http://openlayers.org/en/v3.15.1/apidoc/
Tiếp theo chúng ta sẽ thêm 1 thẻ img để hiển thị legend của lớp. Để lấy được legend trong GeoServer cung cấp cho ta 1 công cụ là GetLegendGraphic. Đại loại là khi bạn trỏ đến đường link như sau thì GeoServer sẽ trả cho bạn một ảnh chú giải: http://localhost:8080/geoserver/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=ten-layer.
Chi tiết từng thuộc tính các bạn xem thêm ở đây: GetLegendGraphic. Đơn giản thì bạn chỉ cần thay link đến GeoServer, thay tên layer vào là xong như code dưới đây:
<img src="http://localhost:8080/geoserver/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=ten-layer" />
  Code tổng hợp:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Openlayers test</title>
<link rel="stylesheet" href="http://openlayers.org/en/v3.15.1/css/ol.css" type="text/css">
<script src="http://openlayers.org/en/v3.15.1/build/ol.js" type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-1.12.3.min.js" type="text/javascript"></script>
<style>
.map {
height: 100%;
width: 100%;
}
</style>
<%-- <link href="bower_components/openlayers3/build/ol.css" rel="stylesheet" />
<script src="bower_components/openlayers3/build/ol.js"></script>
<script src="bower_components/jquery/dist/jquery.min.js"></script>--%>
<script type="text/javascript">
$("#document").ready(function () {
var format = 'image/png';
var bounds = [587376.125, 2263541.25,
589508.8125, 2266077];
var ThuaDat = new ol.layer.Image({
source: new ol.source.ImageWMS({
ratio: 1,
url: 'http://localhost:8080/geoserver/ThaiBinh/wms',
params: {
'FORMAT': format,
'VERSION': '1.1.1',
STYLES: '',
LAYERS: 'ThaiBinh:TD12457',
}
})
});
var projection = new ol.proj.Projection({
code: 'EPSG:3405',
units: 'm',
axisOrientation: 'neu'
});
var map = new ol.Map({
target: 'map',
layers: [
ThuaDat
],
view: new ol.View({
projection: projection
})
});
//map.getView().fitExtent(bounds, map.getSize());
map.getView().fit(bounds, map.getSize());
$("#chkThuaDat").change(function () {
if($("#chkThuaDat").is(":checked"))
{
ThuaDat.setVisible(true);
}
else
{
ThuaDat.setVisible(false);
}
});
});
</script>
</head>
<body>
<div id="map" class="map"></div>
<input type="checkbox" id="chkThuaDat" checked /><label for="chkThuaDat">Thửa đất</label>
<img src="http://localhost:8080/geoserver/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=ThaiBinh:TD12457" />
</body>
</html>
  Hen gặp lại các bạn �� các bài sau nhé.
Tác giả: Đỗ Xuân Cường
Nguồn bài viết: cuongdx313.wordpress.com
Xem nguyên bài viết tại : [Xây dựng WebGIS #8] – Bật tắt layer, hiển thị Legends
0 notes
jochenhayek · 7 years ago
Text
DBCP: database connection pooling (service)
DBCP: database connection pooling (service)
https://en.wikipedia.org/wiki/Apache_Commons
http://commons.apache.org/proper/commons-dbcp/
 — this one lists (most of) the following links:
http://commons.apache.org/proper/commons-dbcp/apidocs/
http://commons.apache.org/proper/commons-dbcp/apidocs/org/apache/commons/dbcp2/package-summary.html#package_description
https://git-wip-us.apache.org/repos/asf?p=commons-dbcp.git
https://git-wip-us.apach…
View On WordPress
0 notes
giriton-en · 6 years ago
Text
Improved REST api
For even easier integration to other systems, we are gradually adding more REST api methods. New methods have been added for complete department management, user relocation between departments, shift management and shift planners.
REST api documentation including instructions for how to use it is here: https://is.giriton.com/apidoc/
0 notes
toastkidjp · 8 years ago
Text
HTTP ステータスコードの定数をどうするか?
問題
Apache の HTTP Client を OkHttp に置き換える際、HTTP ステータスコードの定数をどうするか?調べてみたら Qiita に書くほどのことでもなかったのでここに書く。
背景
Android SDK では Apache の HTTP Client がデファクトスタンダードだった(と思う、少なくとも私の会社では HTTP Client のコードの方が良く見る)のに、突然 Android 5.1 で deprecated 扱いされて、Android 6 以降は標準から消えるというすさまじいことをやってくれていた。Android で非同期通信をするためのライブラリに Volley というのがあったのだが、それが Http Client に依存していたので、6系からは(build.gradle に設定を記述しないと)使えなくなるとかいうギャグみたいな状況になっていたという。
で、Android アプリ開発者たちに代替としてもてはやされた HTTP Client が、Square 社の開発した OkHttp である。Kotlin の影響を受けたらしい現代的なインターフェイスを備えるこのライブラリはコードを書く楽しさのある素敵な一品で、Android SDK の依存がないので通常の Java アプリケーションでも使うことができる。実際私は社内の Scala のアプリケーション開発でこのライブラリをゴリ押しして採用させた。
実はなかった
前置きが長くなった。Apache の HTTP ライブラリには HttpStatus でステータスコードを示す定数が一通り定義されている。
https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpStatus.html
……が、OkHttp 3系にはそれらしきクラスや定数がなかった。なぜだ。
代替案
調べてみたところ、HttpURLConnection にステータスコードを示す定数が一通り定義してあるようだ。
https://docs.oracle.com/javase/jp/8/docs/api/constant-values.html#java.net.HttpURLConnection.HTTP_ACCEPTED
まあ、これを使えばよいのかな……static import すれば HTTP_OK だけで済むわけだし……
実際、 OkHttp3 内部では
軽く見てみたところ、Response クラスで思いっきり上記の定数を使っていたという。
https://github.com/square/okhttp/blob/7135628c645892faf1a48a8cff464e0ed4ad88cb/okhttp/src/main/java/okhttp3/Response.java#L26-L31
そして、ごく一部の定数だけは内部的に定義して使っているようだ。
https://github.com/square/okhttp/blob/7135628c645892faf1a48a8cff464e0ed4ad88cb/okhttp/src/main/java/okhttp3/internal/http/StatusLine.java#L26-L28
よくわからない実装方針である……
結論
HttpURLConnection の定数を使おう。あるいは、それらのラッパーenumを作って使うとよい。
0 notes
giriton-cz · 6 years ago
Text
Vylepšené REST api
Pro ještě hladší napojení na další systémy postupně na vaše přání přidáváme více REST api metod. Nově přibyly metody pro kompletní správu středisek, přeřazování uživatelů mezi středisky, správu směn a plánovačů směn.
Dokumentaci REST api včetně instrukcí pro použití naleznete zde: https://is.giriton.com/apidoc/#/
0 notes