Monday, September 12, 2011

Basic ABAP HTTP Request Sample


For various needs using http requests could be a life saver. Here is a simple code snippet.




  data : lv_value type string.

  data : http_client type ref to if_http_client .
  data : lv_url type string.
  data : return type string.

    data : lv_err_string type string ,
           lv_ret_code type sy-subrc .


* Build Url

  concatenate 'http://www.example.com/?param='
               lv_value
               into lv_url.

* Create Client 
  call method cl_http_client=>create_by_url
    exporting
      url    = lv_url
    importing
      client = http_client.

* Send 
  call method http_client->send
    exceptions
      http_communication_failure = 1
      http_invalid_state         = 2.

* Receive
  call method http_client->receive
    exceptions
      http_communication_failure = 1
      http_invalid_state         = 2
      http_processing_failed     = 3.
  if sy-subrc ne 0.
    http_client->response->get_status(
      importing
        code   = lv_ret_code
        reason = lv_err_string
           ).
    message lv_err_string type 'I'.
  endif.

* Now we have the response , parse , display  
* do what you like 
  return = http_client->response->get_cdata( ).




4 comments:

  1. I get the error "http_communication_failure" after calling the method http_client->receive..

    Any idea about how to solve this problem?
    Thank you

    Andrea

    ReplyDelete
    Replies
    1. Hi Andrea ,

      I think, SAP Server that you're working on has no internet connection. You can check it by running any demo browser report (such as SAPHTML_DEMO1) .

      Delete
    2. Hi,
      I am also facing the same issue. when I run the report SAPHTML_DEMO1, I am successful in opening any webpage.
      Jashua

      Delete