All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.vtence.molecule.testing.http.HttpResponse Maven / Gradle / Ivy

There is a newer version: 0.15.0
Show newest version
package com.vtence.molecule.testing.http;

import com.vtence.molecule.helpers.Joiner;
import com.vtence.molecule.http.ContentType;

import java.net.HttpCookie;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpResponse {
    private final int statusCode;
    private final String statusMessage;
    private final Map> headers;
    private final byte[] content;

    public HttpResponse(int statusCode, String statusMessage, Map> headers, byte[] content) {
        this.statusCode = statusCode;
        this.statusMessage = statusMessage;
        this.headers = headers;
        this.content = content;
    }

    public int statusCode() {
        return statusCode;
    }

    public String statusMessage() {
        return statusMessage;
    }

    public String header(String name) {
        List headers = headers(name);
        if (headers.isEmpty()) return null;
        return Joiner.on(",").join(headers);
    }

    public List headers(String name) {
        List values = headers.get(name);
        return values != null ? values : new ArrayList<>();
    }

    public String contentType() {
        return header("Content-Type");
    }

    public Charset charset() {
        if (contentType() == null) return StandardCharsets.ISO_8859_1;

        return ContentType.parse(contentType()).charset(StandardCharsets.ISO_8859_1);
    }

    public Map cookies() {
        Map cookies = new HashMap<>();
        for (String header : headers("Set-Cookie")) {
            for (HttpCookie cookie : HttpCookie.parse(header)) {
                cookies.put(cookie.getName(), cookie);
            }
        }
        return cookies;
    }

    public HttpCookie cookie(String name) {
        return cookies().get(name);
    }

    public String bodyText() {
        return new String(content, charset());
    }

    public byte[] body() {
        return content;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy