사전 준비사항

  1. 새로운 clojure 프로젝트를 생성한다.
  2. clj-http 모듈 사용을 위해서 project.clj 파일의 dependencies 부분에 아래와 같이 추가해준다. (버전은 참고사이트에서 최신 버전을 확인하자)
    (defproject projectname "0.1.0-SNAPSHOT"
      :description "FIXME: write description"
      :url "http://example.com/FIXME"
      :license {:name "Eclipse Public License"
                :url "http://www.eclipse.org/legal/epl-v10.html"}
      :dependencies [ [org.clojure/clojure "1.6.0"]
                      [clj-http "2.2.0"] ])
    

기본 HTTP 요청하기 예제

(require '[clj-http.client :as client])

(client/get "http://httpbin.org/ip")

(println "done")

POST 요청하기 예제

(require '[clj-http.client :as client])

(println (client/post "http://httpbin.org/post"
  {:body "{\"text\": \"test string\"}"
            :headers {"Content-Type" "application/json"}}))

(println "done")

응답

  • client/get 혹은 client/post를 호출했을 때, 응답은 다음과 같은 형식이 되며 실제 HTML은 :body ~ 부분에 오게된다.

    {:orig-content-encoding ..,
     :trace-redirects ..,
     :request-time ..,
     :status ..,
     :headers
     {"Server" ..,
      "Via" ..,
      .. },
     :body .. }
    

  • :body 부분만 추출하기 위해서는 아래와 같이 호출하면 된다.

    (:body (client/get "http://httpbin.org/ip"))
    

참고 사이트

<테스트 환경>
 - OS : Windows 7
 - Leiningen 버전 : 1.0.0
,


사전 설치 요구사항


request 모듈 사용시, 추가적인 request 모듈 설치를 필요로 한다.


npm install request




폼 전송 방법


request.post('http://service.com/upload', {form:{key:'value'}})
// or
request.post('http://service.com/upload').form({key:'value'})
// or
request.post({url:'http://service.com/upload', form: {key:'value'}}, function(err,httpResponse,body){ /* ... */ })




쿠키 저장


로그인 등에서 서버로부터 전달받은 쿠키를 저장하고 이후에 요청에 계속 사용하고 싶을 경우, 아래 방법 중 한가지를 사용한다.


1) 매 요청마다 옵션에 jar: true를 설정


request({
  ...

  jar: true
},
...



2) 요청 전에 디폴트값으로 설정


var request = request.defaults({jar: true})




,


PIP는 파이썬으로 작성된 패키지 소프트웨어를 설치, 관리하는 패키지 관리 시스템이다. 파이썬 2.7.9 이후 버전과 파이썬 3.4 이후 버전은 pip를 기본적으로 포함한다.



사전 준비사항


1) 파이썬 2.7.9 혹은 3.4 이후 버전


기본적으로 pip가 포함되어 있지만, 파이썬 실행 파일과 경로가 다르기 때문에 <파이썬 설치 경로>/scripts를 PATH 환경 변수에 추가해야 한다.


2) 파이썬 2.7.9 혹은 3.4 이전 버전


아래 PIP 사이트에서 get-pip.py 파일을 받아 실행하면 설치할 수 있다. 설치 후 역시 PATH 환경 변수에 추가가 필요하다.


 - https://pip.pypa.io/en/stable/installing/


python get-pip.py





사용 방법


1) 패키지 설치


pip install some-package-name


2) 패키지 제거


pip uninstall some-package-name



,


- 텔레그램 봇으로 채널 포스팅 - 2. Node.js 사용 예제 (1)

- [Node.js] HTML 파싱하기 (cheerio 모듈 사용)


위의 두 글을 참고하면 웹페이지의 특정 class에 해당하는 부분을 추출하여 텔레그램 채널로 보내는 것이 가능하다. (두둥)

var http = require('http');
var https = require('https');
var cheerio = require('cheerio');
  
var options = {
    hostname: 'httpbin.org'
  };
  
function handleResponse(response) {
  var serverData = '';
  response.on('data', function (chunk) {
    serverData += chunk;
  });
  response.on('end', function () {
  
    var $ = cheerio.load(serverData);
  
    var result = $(".bash").text();            // 클래스가 bash인 요소를 선택
    var result2 = result.replace(/(^\s+|\s+$)/g, ""); // 앞뒤의 화이트 스페이스를 제거
    console.log("Find by class : bash -> " + result2);
 
    var options2 = {
      hostname: 'api.telegram.org',
      path: '/bot<텔레그램 봇 토큰>/sendMessage',
      method: 'POST',
      headers: {
          'Content-Type': 'application/json',
      }
    };
      
    var req = https.request(options2, function(res) {
      console.log('Status: ' + res.statusCode);
      console.log('Headers: ' + JSON.stringify(res.headers));
      res.setEncoding('utf8');
      res.on('data', function (body) {
        console.log('Body: ' + body);
      });
    });
    req.on('error', function(e) {
      console.log('problem with request: ' + e.message);
    });
      
    req.write(
        '{"chat_id": "@<채널 ID>", "text": "' + result2 + '"}'
    );
    req.end();
 
  });
}
  
http.request(options, function(response){
  handleResponse(response);
}).end();





,


Node.js를 사용하여 텔레그램 채널에 메세지를 보내는 예제입니다.

<텔레그램 봇 토큰>과 <채널 ID> 부분은 아래 글에서 설명했던 값으로 바꿔줍니다.


 -> 텔레그램 봇으로 채널 포스팅 - 1. 준비 작업



var http = require("https");
var options = {
  hostname: 'api.telegram.org',
  path: '/bot<텔레그램 봇 토큰>/sendMessage',
  method: 'POST',
  headers: {
      'Content-Type': 'application/json',
  }
};

var req = http.request(options, function(res) {
  console.log('Status: ' + res.statusCode);
  console.log('Headers: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (body) {
    console.log('Body: ' + body);
  });
});
req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

req.write(
    '{"chat_id": "@<채널 ID>", "text": "test string"}'
);
req.end();



참고 글


 - [Node.js] HTTP 요청하기 (http 모듈 사용)



,