Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an empty dummy HttpResponse

I am using org.apache.http.HttpResponse

I want to create an empty dummy resposne, I am going to use this to return when errors occur instead of passing back null.

I tried to create one and it has lost of weird params. Can someone tell me how to create one.

like image 621
jax Avatar asked Jun 08 '10 11:06

jax


3 Answers

This version add the entity content and is a little bit more compact:

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion.HTTP_1_1;
import org.apache.http.entity.ContentType.TEXT_HTML;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHttpResponse;
import org.springframework.http.HttpStatus;

public static HttpResponse buildResponse(HttpStatus status, String text){
    
       HttpResponse response = new BasicHttpResponse(HTTP_1_1, status.value(), status.reasonPhrase);
       response.setEntity(new StringEntity(text, TEXT_HTML));
       return response;
    }

Note that I am using the Spring HttpStatus just for my convenience but may be changed with parameters

like image 126
borjab Avatar answered Nov 16 '22 16:11

borjab


Depending on what version of commons you're using, you might want to try DefaultHttpResponseFactory. This is the way that the library creates some of it's responses internally so it may or may not serve your purposes.

import org.apache.http.HttpStatus;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.HttpVersion;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.message.BasicStatusLine;

HttpResponseFactory factory = new DefaultHttpResponseFactory();
HttpResponse response = factory.newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null), null);
like image 30
Brian Avatar answered Nov 16 '22 18:11

Brian


Just implement HttpResponse with no-op methods.

like image 2
Bozho Avatar answered Nov 16 '22 17:11

Bozho