Skip to content

CoAP-to-HTTP Proxy Returns 5.02 Bad Gateway

DodaTech Updated 2026-06-26 1 min read

In this tutorial, you'll learn about CoAP. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

CoAP requests forwarded to an HTTP resource via proxy return 5.02 (Bad Gateway).

Quick Fix

Wrong

proxy.forward('http://api.example.com/data');  // Direct HTTP call from CoAP proxy```

Client receives 5.02 Bad Gateway. Proxy cannot connect to HTTP endpoint.


### Right

```cpp
#include <coap.h>

// CoAP-to-HTTP proxy using libcoap
coap_context_t *ctx = coap_new_context(NULL);

void proxy_get_handler(coap_context_t *ctx, coap_resource_t *res,
                       coap_session_t *session, coap_pdu_t *request,
                       coap_binary_t *token, coap_string_t *query,
                       coap_pdu_t *response) {
  // Forward to HTTP endpoint
  const char *http_url = "http://api.example.com/data?format=json";

  // libcoap handles Proxy-Uri option automatically
  coap_pdu_set_code(response, COAP_RESPONSE_CODE_CONTENT);

  // Map HTTP status to CoAP code
  // 200 → 2.05, 201 → 2.01, 404 → 4.04, 500 → 5.00
  unsigned char buf[] = "{"proxied":true,"data":"from HTTP"}";
  coap_add_data(response, sizeof(buf) - 1, buf);
}```

Client receives 2.05 Content with proxied data from HTTP API.


## Prevention

CoAP-to-HTTP proxying translates between CoAP and HTTP. The proxy receives CoAP requests, makes HTTP requests, and translates responses. CoAP response codes map to HTTP: 2.05→200, 2.01→201, 4.04→404, 5.00→500. The Proxy-Uri option in CoAP specifies the HTTP target. Content-Format must be translated between CoAP and HTTP media types.

DodaTech engineers apply these same patterns across Doda Browser, DodaZIP, and Durga Antivirus Pro for production IoT reliability.

## FAQ

<details style="margin-bottom:12px;border:1px solid #e2e8f0;border-radius:10px;overflow:hidden"><summary style="cursor:pointer;padding:14px 18px;font-weight:600;font-size:1.05rem;background:#f8fafc;border-bottom:1px solid #e2e8f0;color:#1e293b">### What is the response code mapping?</summary><div style="padding:14px 18px;color:#475569;line-height:1.7;background:#fff"><p>CoAP 2.05=HTTP 200, 2.01=201, 2.04=204, 4.00=400, 4.04=404, 4.05=405, 5.00=500, 5.02=502.</p>
<h3 id="can-proxy-translate-content-format">Can proxy translate Content-Format?</h3><p>Yes, but media type IDs differ. CoAP uses numeric IDs (0=text/plain, 50=application/json) while HTTP uses MIME types. Proxy must convert.</p>
<h3 id="what-is-proxy-uri-option">What is Proxy-Uri option?</h3><p>A CoAP option that carries the full HTTP URI the proxy should forward to. Used for cross-protocol proxying.</p>
</div></details>

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro