HTTP General

TCP/UDP Ports and services

20
FTP
File Transfer Protocol
21
FTP
File Transfer Protocol (Control)
22
SSH
Secure Shell
23
Telnet
Telnet
25
SMTP
Simple Mail Transfer Protocol
53
DNS
Domain Name System
80
HTTP
Hypertext Transfer Protocol
110
POP3
Post Office Protocol v3
119
NNTP
Network News Transfer Protocol
123
NTP
Network Time Protocol
143
IMAP
Internet Message Access Protocol
161
SNMP
Simple Network Management Protocol
194
IRC
Internet Relay Chat

Burp Suite

Préparations de Burpsuite
Avant de ce lancer dans la recherche de faille, il faut connecter Firefox avec notre proxy dans les paramètres du navigateur.
Vérifier intercept is off
Pour actualiser la fenêtre, appuyer sur forward
Vous pouvez installer l'extension de Firefox nommé Proxyfox pour activer votre proxy pour les recherches de failles

Compatibility's Request

Même si toutes les requêtes (sauf TRACE) sont compatibles, les navigateurs recommandés sont FireFox, Chrome, Brave et Opera.

Methods

GET
Demande une représentation de la ressource. Elle est utilisée afin de récupérer des données.
HEAD
Demande une réponse identique à GET mais uniquement l'en-tête
POST
Utilisée pour envoyer une entité vers la ressource. Engendre un changement d'état ou des effets de bords sur le serveur.
PUT
Remplace toutes représentation actuelles de la ressource visée par la requête
DELETE
Supprime la ressource indiquée
CONNECT
Établit un tunnel vers le serveur identifié par la ressource
OPTIONS
Utilisée pour décrire les options de communications avec la ressource
TRACE
Réalise un message de test a/r en suivant le chemin de la ressource visée
PATCH
Utilisée pour appliquer des modifications partielles à une ressource

2xx: Successful responses

200 [OK] - The request has succeeded. The meaning of the success depends on the HTTP method
201 [Created] - The request has succeeded and a new resource has been created as a result. This is typically the response sent after POST requests, or some PUT requests.
202 [Accepted] - The request has been received but not yet acted upon. It is noncommittal, since there is no way in HTTP to later send an asynchronous response indicating the outcome of the request. It is intended for cases where another process or server handles the request, or for batch processing.
203 [Non-Authoritative Information] - This response code means the returned meta-information is not exactly the same as is available from the origin server, but is collected from a local or a third-party copy. This is mostly used for mirrors or backups of another resource. Except for that specific case, the "200 OK" response is preferred to this status.
204 [No Content] - There is no content to send for this request, but the headers may be useful. The user-agent may update its cached headers for this resource with the new ones.
205 [Reset Content] - Tells the user-agent to reset the document which sent this request.
206 [Partial Content] - This response code is used when the Range header is sent from the client to request only part of a resource.
207 [Multi-Status] (WebDAV) - Conveys information about multiple resources, for situations where multiple status codes might be appropriate.
208 [Already Reported] (WebDAV) - Used inside a
<dav:propstat>
response element to avoid repeatedly enumerating the internal members of multiple bindings to the same collection.
226 [IM Used] (HTTP Delta encoding) -

1xx Informational response

100 [Continue] - This interim response indicates that everything so far is OK and that the client should continue the request, or ignore the response if the request is already finished.
101 [Switching Protocol] - This code is sent in response to an Upgrade request header from the client, and indicates the protocol the server is switching to.
102 [Processing] - This code indicates that the server has received and is processing the request, but no response is available yet.
103 [Early Hints] - This status code is primarily intended to be used with the Link header, letting the user agent start preloading resources while the server prepares a response.

Use Netcrat to Determine HTTP Methods

#! /bin/bash
for method in GET POST PUT TRACE CONNECT OPTIONS;
do
  printf "$method / HTTP/1.1\r\nHost:domain\r\n\r\n" | nc domain 80
done
Can manually type HTTP commands into Netcat or use a bash script like the one above.

Websocket Tools

Many tools do not handle Websocket to capture, intercept, or fuzz
Wireshark can capture raw network traffic but cannot parse
ZAP was one of the first to support interception and fuzzing of Websocket connections

Websocket

Designed to establish connection to a back-end server allowing for long-term communciation
Supports bidirectional communication over a single TCP socket
Designed to handle blocked ports/network restrictions
Depends on the server and the client support for JavaScript and HTML5
Handshake over HTTP(S):
ws :// Protocol handler initiates the request
wss :// for sercure is more widely used

Attacker's Perspective of HTTP

Look for methods that should NOT be supported: PUT, DELETE, CONNECT
TRACE can help map network architecture
Check for method interchange, which can ease XSS attacks and scripting because parameters can be passed in the URL

DELETE Method

Removes the resource specified by the URL
Could lead to DoS
Can be used to change configurations, such as deleting .htaccess file
Should not be supported on public internet-facing servers.

PUT Method

Uploads data tot he location specified by the URL
Data upload is the HTTP payload
Should not be supported on public internet-facing servers.

OPTIONS Method

Asks the server to return the list of request methods supports
Enables an attacker to determine methods for attacks

TRACE Method

Will echo the request as seen by the server back at the client
It is for diagnostic purposes
Enables the attacker to see any changes made by proxies (inbound or outbound)

POST Method

Requests a web resource but passes parameters via the HTTP payload
Can still be manipulated
Can be changed to a GET for simpler scripting if the app supports Method Interchange and register_globals is how this happens in PHP
Parameters will not get logged

GET Method

Used to obtain a web resource from the server by passing parameters via URL
Easily manipulated by attackers
Could be dangerous for authentication-related and session tracking parameters
Easier to script against an app using GET
Enables an attacker to test requests without waiting for payload

Request Methods

GET
OPTIONS
POST
CONNECT
HEAD
PUT
TRACE
DELETE
Some other web apps and/or servers add other methods.

Query String Formats

Typical format
index.php?id=42&name=Beeblebrox
Apache's mod_rewrite module
index.php/id/42/name/Beeblebrox
Data parsed by server-side code
index.php/id=42$name=Beeblebrox
Data used by an app executed using a system call in the web app
index.php?param=id:42&param=name:Beeblebrox
Used to pass data via URL request, they are determined by the web application developer and/or the production environment running the application.

Uniform Resource Identifier (URI)

Made of various pieces in the following order:
Protocol
username:password (blocked by modern web browsers)
Host and domain name
Port defaults
Actual resource on that server
Question mark
Often used interchangeably with URL

User-Agent

Mozilla/5.0
Compliant with historical standards
Trident/7.0
rv:11.0 Internet Explorer 11.0
Windows NT 10
Windows 10
Windows NT 6.3
Windows 8.1/2012R2
Windows NT 6.2
Windows 8/2012
Windows NT 6.1
Windows 7/2008R2
Windows 6.0
Vista/2008
Web clients, often browsers.

Example HTTP 1.1 Response

HTTP/1.1 200 OK

Content-Type: text/html;

charset=UTF-8

Server: Apache/2.4.7 (Ubuntu)

Date: Tue, 24 Oct 2017 15:51:10 GMT

Content-length: 6243
The status code is the result of the request.
Server token is the string returned by the web server identifying itself.
Server Time is the time stamp based on the server's time and date.
Content Length is the length of the response. The header ends with a blank line.

Example HTTP 1.1 Request

GET /search HTTP/1.1

Accept: /

Accept-Language: en-us

User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko

Host: www.google.com

Proxy-Connection: Keep-Alive

Cookies SESSIONID=c953ef6978d4525b35620e9f70234aa9; ANSWER=42;

Content-length: 0
This is a GET request.
The user agent string identifies the type of client software and summarizes its capabilities.
The cookie provides one or more state variables previously set by a server on this client.
The payload of this request has no content. Keep in mind the header ends with a blank line.

HTTP/2

Binary Protocol
Improved compression
Push Promise
Web server sends content without request
Multiplexed
Requests and responses can be received in parallel
HPACK (RFC 7541)
Header compression
Encryption
Not required by default
Primary focus is faster performance.

HTTP/1.1

RFC
2616, later replaced by 7230-7235
Methods Supported
GET, HEAD, POST, PUT, DELETE, OPTION
Virtual Host Support
Yes
Enabled persistent connections. Host header is mandatory.

HTTP/1.0

RFC
1945
Methods Supported
GET, HEAD, POST, PUT, DELETE
Responses
HTML, non-HTML (text, binary, images)
Virtual Host Support
none
Released in May '96, first formal HTTP standard. Formalized the misspelling of "referrer".

HTTP/0.9

RFC
none
MEthod Supported
GET
Virtual Host Support
none
Responses
HTML only
1 GET = 1 TCP connection

Web v1

No Authentication
No encryption
Sessionless

Activación HTTPS en Nginx

Crear carpeta para los certificados:
sudo mkdir /etc/nginx/ssl
Crear certificados y claves:
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/server.key -out /etc/nginx/ssl/server.crt

Autenticación en Nginx

Instalar herramienta htpasswd para generar contraseña:
sudo apt install apache2-utils
Generar usuario y contraseña:
sudo htpasswd /etc/nginx/.htpasswd usuario
Editar configuración nginx:
sudo nano /etc/nginx/sites-available/nombre

Crear sitio web en Nginx

Crear carpeta para el sitio:
sudo mkdir -p /var/www/nombre/html
Carpeta sea de usuario web:
sudo chown -R www-data:www-data /var/www/nombre/html
Conceder permisos para evitar error:
sudo chmod -R 755 /var/www/nombre/html
Editar archivo de configuración:
sudo nano /etc/nginx/sites-available/nombre
Crear archivo simbólico para alta automática:
sudo ln -s /etc/nginx/sites-available/nombre /etc/nginx/sites-enabled/
Reiniciar servidor:
sudo systemctl restart nginx

Instalación y configuración de Nginx

Actualizar repositorios:
sudo apt update
Actualizar sistema:
sudo apt upgrade
Instalar Nginx:
sudo apt install nginx
Comprobar instalación:
systemctl status nginx
Ruta registros correctos del servidor:
/var/log/nginx/access.log
Ruta registros erróneos del servidor:
/var/log/nginx/error.log
Reiniciar servidor:
sudo systemctl restart nginx

Protocolos HTTP y HTTPS

Protocolo HTTP
Protocolo HTTPS
El protocolo de transferencia de hipertexto (HTTP, Hypertext Transfer Protocol) es el motor que da vida a Internet, ya que es la base para la web
Protocolo de aplicación basado en el protocolo HTTP, destinado a la transferencia segura de datos de hipertexto, es la versión segura de HTTP.
Funcionamiento:
Funcionamiento
1. Un usuario accede a una URL
1. Cliente envía petición de sesión segura
2. El cliente Web descodifica la URL
2. Servidor envía certificado X.509
3. Se abre una conexión TCP/IP con el servidor
3. Cliente autentica certificado
4. El servidor devuelve la respuesta al cliente
4. Cliente genera clave simétrica aleatoria
5. Se cierra la conexión TCP
5. Cliente y servidor conocen y utilizan clave asimétrica.

Plataformas Web libres y propietarias

Plataformas Web Libres
Plataformas Web Propietarias
LAMP: Linux, Apache, MySQL, PHP
WISA: Windows, InternetInformationServices (IIS), SQL Server, ASP
Otras plataformas:
WAMP (Windows-Apache-MySQL-PHP)
WIMP (Windows-IIS-MySQL-PHP)
LNMP (Linux + Nginx + MySQL o MariaDB + PHP)
WNMP (Windows + Nginx + MySQL o MariaDB + PHP)

Servidores de Archivos y Directorios

Servidores de Archivos
Servidores de Directorios
Se utilizan principalmente para implementar las aplicaciones en el servidor donde se ejecutarán
Permite gestionar información administrativa sobre el entorno de una aplicación web, facilitan la gestión de información relacionada con la explotación de aplicaciones web.
Ejemplos: ProFTPD o vsftpd (Linux), Microsoft Internet Information Server (Windows).
Ejemplos: OpenLDAP (Linux), Active Directory (Windows).

Servidores Web y de Aplicaciones

Servidores Web
Servidores de Aplicaciones
Servidor que permite el acceso a recursos a través del protocolo HTTP, permiten consultar, cargar y eliminar recursos del servidor.
Servidor que ofrece a los clientes un servicio de ejecución de aplicaciones, es un software que controla la ejecución de programas.
Ejemplos: Apache o Nginx (Linux), Microsoft Internet Information Server (Windows)
Ejemplos: GlassFish (servidor Java EE, Oracle), Tomcat o Microsoft Internet Information Server (servidor .NET)

Arquitecturas Web

Modelo Cliente-Servidor
Aplicaciones web pequeñas, clientes realizan petición, servidor devuelve resultado
Modelo Cliente-Servidor con servidores encadenados
Tareas más complejas, distribuir subtareas en varios servidores
Modelo Peer-to-Peer (P2P)
Todas las computadoras actúan simultáneamente como clientes y servidores

Proxy

HTTP Proxy servers are act as an intermediary for client-to-server requests such as HTTP.

A forward proxy is a type of proxy server that receives and forwards requests in order to cache and facilitate access to a wide range of web servers.

A reverse proxy is a type of proxy server that receives and forwards requests in order to do load-balancing for a group of web servers.

About MIME types

The
Accept
and
Content-Type
headers use MIME types to specify the type of message content.

There are basic MIME types for simple files and web formats:
text/plain
,
text/html
,
application/xml
,
application/json
,
application/octet-stream
,
text/css
,
text/javascript
...

There are MIME types for all known file formats:
image/jpeg
,
image/png
,
audio/mpeg
,
application/pdf
,
application/zip
,
font/woff
,
video/mp4
...

There are specific MIME types related to browsers and APIs:
multipart/mixed
,
multipart/form-data
,
multipart/byteranges
,
application/x-www-form-urlencoded
...

Sometimes, extra information are added to a type. Text format can have a charset specification:
text/plain;charset=UTF-8


See: RFC-2045, RFC-2046, RFC-2047, RFC-4288, RFC-4289, RFC-2049; and MDN: MIME type
Examples:
Content-Type: text/plain;charset=utf-8

Protocol versions

HTTP/0.9 and HTTP/1.0
History: RFC-1945 (actual)

HTTP/1.1
This is the most used HTTP version.

History: RFC-2068 (obsolete), RFC-2616 (obsolete), RFC-7230 (actual)

HTTP/2
According to W3Techs, as of March 2019, 33.9% of the top 10 million websites supported HTTP/2.

History: RFC-7540 (actual)

HTTP/3
Also called HTTP-over-QUIC, it is the upcoming major version of HTTP.

Notes

All specifications in this document have been simplified from the official HTTP standard. Always refer to the RFCs if necessary.

RFC-7230: Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing

Content size & streaming

When a message body is exchanged, the receiver must be able to determine when the message is complete (or how many bytes should be received to consider the body complete).

The main operating way is to use the
Content-Length
header with the size (in bytes) of the body that is to come.

When a streaming method is desired, an alternative way is to use the
Transfer-Encoding: chunked
header and to follow the Chunked transfer encoding protocol.

Common HTTP Response Headers

Cache-Control
: Indicates client caching conditions
Content-Length
: Length of the response body in bytes
Content-Type
: MIME type of the response body
Expires
: Client is allowed to keep the resouce in cache
Location
: Redirection URL
Server
: name of the server software
Set-Cookie
: new cookies that should be stored client-side
There are many more available.
You can create your own headers.

HTTP Status Codes

1xx
Informational
100
Continue
2xx
Successful
200
OK
201
Created
202
Accepted
204
No Content
3xx
Redirection
301
Moved permanently
302
Found
304
Not Modified
308
Permanent Redirect
4xx
Client Error
400
Bad Request
401
Unauthorized
403
Forbidden
404
Not Found
405
Method Not Allowed
5xx
Server Error
500
Internal Server Error
502
Bad Gateway
503
Service Unavailable
504
Gateway Timeout
There are many other codes; these are the most used. You should not create your own codes.

Common HTTP Request Headers

Accept
List of MIME types supported
Accept-Language
List of languages read by the user
Content-Length
Length in bytes of the request body
Content-Type
MIME type of the request body
Cookie
List of cookies stored by the client
Host
Host name of the website
User-Agent
Identification string for the web browser
There are many more available.
You can create your own headers.

HTTP Request Methods

GET
: used to retrieve a resource. Has no request body.
POST
: used to submit a new resource (path) or send data. Usually has a body.
HEAD
: used to preview the result of a
GET
operation. Has no request body and no respond body.
PUT
: used to submit an update to an existing resource
DELETE
: used to delete the specified resource
TRACE
: echoes the received request for tracing purposes
OPTIONS
: verify the server supports a specified request (see Preflight requests)
CONNECT
: used by HTTPS
PATCH
: allows partial modification of a resource

HTTP Response Body

The is usually a response body after the response headers. It can be a file or a specific form of data.

The Content-Type header must be filled with a MIME type to indicate the type of content.

The body is separated from the headers by two line feeds (\n).

HTTP Response Headers

"
NAME: VALUE
"*

NAME:
[A-Za-z0-9][A-Za-z0-9-]+

VALUE: US-ASCII octets

Headers are extra information for the response. There are many standard headers and you can create your own.

See Common HTTP Response Headers

HTTP Response Line

Format:
PROTOCOL STATUS REASON


PROTOCOL:
HTTP/1.1

STATUS: Any HTTP Status Code
REASON: A reason message

The reason message is usually the label associated to the status code. Some APIs may use this text field to specify an error message.
Examples:
HTTP/1.1 200 OK

HTTP/1.1 404 Not Found

HTTP Request Body

If the HTTP method used is
POST
or
PUT
, the request may be followed by a body. It can be a file or a specific form of data.

The
Content-Type
header must be filled with a MIME type to indicate the type of content.

The body is separated from the header by two line feeds (
\n
).

HTTP Request Headers

"
NAME: VALUE
"*

NAME:
[A-Za-z0-9][A-Za-z0-9-]+

VALUE: US-ASCII octets

Headers are extra information for the request. There are many standard headers and you can create your own.

See Common HTTP Request Headers
Example set of headers:
Host: en.wikipedia.org

User-Agent: Mozilla/5.0 Firefox/64.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8

Accept-Language: en-GB,en-US;q=0.8,en;q=0.6,fr-FR;q=0.4,fr;q=0.2

Accept-Encoding: gzip, deflate, br

Connection: keep-alive

Cookie: Auth=8QXA5fSQeZAEKZVG6iRjMWvQ8KtQKAaj

HTTP Request Line

Format: "
METHOD PATH PROTOCOL
"

METHOD:
GET
,
HEAD
,
POST
,
PUT
,
DELETE
,
TRACE
,
OPTIONS
,
CONNECT
,
PATCH

PATH: the path of the resource
PROTOCOL:
HTTP/1.1
Example:
GET /images/logo.png HTTP/1.1

Request and Response Messages

The HTTP protocol consist into a request message, sent from a client to a web server; and a response message, sent from the server to the originating client.

Request message general format:
HTTP Request Line

HTTP Request Headers

(empty line)

HTTP Request Body


Response message general format:
HTTP Response Line

HTTP Response Headers

(empty line)

HTTP Response Body

Kullanılmayan Kodlar

306
Proxy Değiştirilmeli
416
İstek uzunluğu karşılanamıyor
506
Yeniden yönlendirme hatası

Sunucu Hata Kodları

500
Dahili Sunucu Hatası
Sunucu ayarları hatalı
501
Uygulanamadı
Sunucu isteğin tamamına ait fonksiyonları desteklemiyor
502
Kötü gateway
Sunucu isteği gerçekleştiren aradaki sunucu isteğinin geçersiz olduğunu algıladı
503
Servis Hatası
Servis geçici olarak devre dışı. Servis aktif hale geldiğinde sunucu tekrar deneme yapabilir.
504
Gateway zaman aşımı
Ağ geçidi ya da proxy zaman aşımına uğradı
505
HTTP versiyon desteklenmiyor
İstemci tarafından kullanılan http versiyonu desteklenmiyor

Tamamlanamayan İstek Hataları

400
Kötü İstek
İstekte syntax hatası
401
Yetkili Değil
Kullanıcı doğrulaması gerektiriyor
402
Ödeme gerekli
(reserv hata kodu)
403
Yasak
Bu bölge istemci için yasaklanmış
404
Bulunamadı
Burada böyle bir şey yok
405
Metoda izin verilmedi
Header metodu sunucuya uygun değil
406
Kabul edilemez
İstek format ile sunucu formatı farklı
407
Proxy yetkisi gerek
İstemci öncelikle kendi yetkisini proxy üzerinde etkinleştirmesi gerekli
408
Zamanaşımı
Tekrar gönderilebilir
409
Çakışma
İstemci isteği başka bir istekle çakıştı,
410
Yok (Gitmiş)
İstek kaynağı buradan gitmiş
411
Tamamı gerekli
İstemcinin içerik başlığının tamamı gerekli
412
Ön koşul hatası
Tanımlanmış ön koşul kondisyonları eşleşmiyor
413
İstek çok büyük
İstemcinin içerik paketi çok büyük
414
URI çok uzun
İstenilen URI çok uzun
415
Desteklenmeyen içerik
İstemci içeriği desteklenmiyor
417
Beklenti hatası
İstemci başlığı gereksinimleri karşılamadığı için reddedildi

Yönlendirilen İstekler

300
Birden fazla seçenek
301
Kalıcı olarak taşındı
302
Geçici olarak taşındı
303
Diğerini gör
304
Düzenlenmedi
305
Proxy Kullan
307
Geçici Yönlendirme

İstek Başarılı Kodları

200
OK
İstek yerine getirildi
201
Oluşturuldu
İstek yapılan URI oluşturuldu
202
Kabul edildi
İstek kabul edildi ancak işlem devam ediyor
203
Yetkisiz Bilgilendirme
Cevap dönülen bilgi başka bir sunucudan getirildi
204
İçerik Yok
İstek tamamlandı ancak herhangi bir içerik bulunmamaktadır
205
İçerik Sıfırlanmalı
İstemcinin dökumanı aynı değerler ile sıfırlaması gerekli
206
Parçalı İçerik
Sunucu eksik gerçekleşen GET isteğinin eksik bölümlerini tamamladı

Bilgilendirme Kodları

100
Devam
Sunucu geri kalan paketi almaya hazır
101
Protokol Değiştirme
İstemcinin paket başlığında yer alan protokolün uygulama protokolüyle değiştiği anlaşıldı

Reference

 private requestUrl: string = 'http://localhost:4000/posts';

  getData(id : number) : Observable<Post> {
    return this.http.get(
${this.requestUrl}/${id}
)       .map(this.mapResponse)       .catch(this.handleError)   }
Using the back ticks to specify internal references ``
referencing the content in ${}

Observable - Subscribe

observerOrNext
PartialObserver<T> | ((value: T) => void)
error
(error: any) => void
complete
() => void
this.service.getData(10).subscribe(
(data : Post) => {
this.result = data;
},
(error : any) => {
console.error(error);
}
)

Rx - catch

  getData(id : number) : Observable<Post> {
    return this.http.get(
${this.requestUrl}/${id}
)       .map(this.mapResponse)       .catch(this.handleError)   }   handleError(error: any): Observable<any> {     console.error('An error occurred', error);     return Observable.throw(error.json() || 'Server error');   }
The catch reference is there to handle exceptions that are thrown. This gives you an opportunity to handle them in a graceful manner.
All rx operations return an observable.

Rx - Map

getData(id : number) : Observable<Post> {
    return this.http.get(
${this.requestUrl}/${id}
)       .map(this.mapResponse)       .catch(this.handleError)   }   mapResponse(response : Response) : Post {     return response.json();   }
The map() function takes in a lambda function or a reference to a function that will execute the procedure and return the mapped result.
Accepts (res : Respone) and returns a result.

Sample Delegate

import { Injectable } from '@angular/core';
import {Http, Response, Headers, RequestOptions} from "@angular/http";
import 'rxjs/Rx';
import {Observable} from "rxjs";
import {Post} from "./http/post.class";


@Injectable()
export class HttpService {

  constructor(private http: Http) { }

  private requestUrl: string = 'http://localhost:4000/posts';

  //Do all methods and observable options

  getData(id : number) : Observable<Post> {
    return this.http.get(
${this.requestUrl}/${id}
)       .map(this.mapResponse)       .catch(this.handleError)   }   handleError(error: any): Observable<any> {     console.error('An error occurred', error);     return Observable.throw(error.json() || 'Server error');   }   mapResponse(response : Response) : Post {     return response.json();   }   addData(body : Post) : Observable<Post> {     let bodyString = JSON.stringify(body);     let header = new Headers({       'Content-Type' : 'application/json'     });     let options = new RequestOptions({       headers : header     });     return this.http.post(
${this.requestUrl}
, bodyString, options)       .map(this.mapResponse)       .catch(this.handleError);   }   updateData(body : Post) : Observable<Post> {     let bodyString = JSON.stringify(body);     let header = new Headers({       'Content-Type' : 'application/json'     });     let options = new RequestOptions({       headers : header     });     return this.http.put(
${this.requestUrl}/${body.id}
, bodyString, options)       .map(this.mapResponse)       .catch(this.handleError);   }   deleteData(body : Post) : Observable<Post> {     return this.http.delete(
${this.requestUrl}/${body.id}
)       .map(this.mapResponse)       .catch(this.handleError);   } }

Headers


class Headers {
  staticfromResponseHeaderString(headersString: string) : Headers
  constructor(headers?: Headers|{[name: string]: any})
  append(name: string, value: string) : void
  delete(name: string) : void
  forEach(fn: (values: string[], name: string, headers: Map<string, string[]>) => void) : void
  get(name: string) : string
  has(name: string) : boolean
  keys() : string[]
  set(name: string, value: string|string[]) : void
  values() : string[][]
  toJSON() : {[name: string]: any}
  getAll(name: string) : string[]
  entries()
}

RequestOptionsArgs


interface RequestOptionsArgs {
  url : string
  method : string|RequestMethod
  search : string|URLSearchParams
  headers : Headers
  body : any
  withCredentials : boolean
  responseType : ResponseContentType
}

Http Verbs

GET
get(url: string, options?: RequestOptionsArgs) : Observable<Response> Performs a request with get http method.
POST
post(url: string, body: any, options?: RequestOptionsArgs) : Observable<Response> Performs a request with post http method.
PUT
put(url: string, body: any, options?: RequestOptionsArgs) : Observable<Response> Performs a request with put http method.
DELETE
delete(url: string, options?: RequestOptionsArgs) : Observable<Response> Performs a request with delete http method.
PATCH
patch(url: string, body: any, options?: RequestOptionsArgs) : Observable<Response> Performs a request with patch http method.
HEAD
head(url: string, options?: RequestOptionsArgs) : Observable<Response> Performs a request with head http method.
OPTIONS
options(url: string, options?: RequestOptionsArgs) : Observable<Response> Performs a request with options http method.

Using Angular HTTP

constructor(private http: Http) {}

Starting Up

@NgModule({
     declarations: [],
     imports: [HttpModule],
     bootstrap: [],
     providers: []
})

Server Error (5xx)

500
Internal Server Error
501
Not Implemented
502
Bad Gateway
503
Service Unavailable
504
Gateway Timeout
505
HTTP Version Not Supported

Client Error (4xx)

400
Bad Request
401
Unauthorized
402
Payment Required
403
Forbidden
404
Not Found
405
Method Not Allowed
406
Not Acceptable
407
Proxy Authentication Required
408
Request Timeout
409
Conflict
410
Gone
411
Length Required
412
Precondition Failed
413
Request Entity Too Large
414
Request-URI Too Long
415
Unsupported Media Type
416
Requested Range Not Satisfiable
417
Expectation Failed

Source

Created from the official documentation from W3.org (https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)

Redirection (3xx)

300
Multiple Choices
301
Moved Permanently
302
Found
303
See Other
304
Not Modified
305
Use Proxy
306
(Unused)
307
Temporary Redirect

Successful (2xx)

200
OK
201
Created
202
Accepted
203
Non-Authoritative Information
204
No Content
205
Reset Content
206
Partial Content

Informational (1xx)

100
Continue
101
Switching Protocols

HTTP Code Comments

WebDAV
WebDAV extension
1.1
HTTP/1.1
GET, POST, PUT, POST
For these methods only
IE
IE extension
MS
MS extension
nginx
nginx extension
2518, 2817, 2295, 2774, 3229, 4918, 5842
RFC number
draft
Proposed draft
nostd
Non standard extension
res
Reserved for future use
unused
No more in use, deprecated
Wikipedia was used to produce all HTTP codes content:
http://en.wikipedia.org/wiki/HTTP_status

5xx: HTTP Server Error Codes

500
Internal Server Error
501
Not Implemented
502
Bad Gateway
503
Service Unavailable
504
Gateway Timeout
505
HTTP Version Not Supported
506
Variant Also Negotiates 2295
507
Insufficient Storage WebDAV 4918
508
Loop Detected WebDAV 5842
509
Bandwidth Limit Exceeded nostd
510
Not Extended 2774
511
Network Authentication Required draft
598
Network read timeout error nostd
599
Network connect timeout error nostd

4xx: HTTP Client Error Code

400
Bad Request
401
Unauthorized
402
Payment Required res
403
Forbidden
404
Not Found
405
Method Not Allowed
406
Not Acceptable
407
Proxy Authentication Required
408
Request Timeout
409
Conflict
410
Gone
411
Length Required
412
Precondition Failed
413
Request Entity Too Large
414
Request-URI Too Long
415
Unsupported Media Type
416
Requested Range Not Satisfiable
417
Expectation Failed
418
I'm a teapot 2324
422
Unprocessable Entity WebDAV 4918
423
Locked WebDAV 4918
424
Failed Dependency WebDAV 4918
425
Unordered Collection 3648
426
Upgrade Required 2817
428
Precondition Required draft
429
Too Many Requests draft
431
Request Header Fields Too Large draft
444
No Response nginx
449
Retry With MS
450
Blocked By Windows Parental Controls MS
451
Unavailable For Legal Reasons draft
499
Client Closed Request nginx

3xx: HTTP Redirection Codes

300
Multiple Choices
301
Moved Permanently
302
Found
303
See Other 1.1
304
Not Modified
305
Use Proxy 1.1
306
Switch Proxy unused
307
Temporary Redirect 1.1
308
Permanent Redirect 7538
307 and 308 are similar to 302 and 301, but the new request method after redirect must be the same, as on initial request.

2xx: HTTP Successful Codes

200
OK
201
Created
202
Accepted
203
Non-Authoritative Information 1.1
204
No Content
205
Reset Content
206
Partial Content
207
Multi-Status WebDAV 4918
208
Already Reported WebDAV 5842
226
IM Used 3229 GET

1xx: HTTP Informational Codes

100
Continue
101
Switching Protocols
102
Processing WebDAV
103
Checkpoint draft POST PUT
122
Request-URI too long IE7
Comments