I am using org.apache.http.HttpResponse
I want to create an empty dummy resposne, I am going to use开发者_如何学Python 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.
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);
Just implement HttpResponse
with no-op methods.
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
Indeed, implementing a HttpServletResponse seems quite a lot work, and you'll be dependent on the actual Servlet implementation.
I think I'd use request.getRequestDispatcher("/dummy.html").forward(request, response)
You can create a method that returns HttpResponse with the status code:
public HttpResponse<String> createDummyResponse(int statusCode) {
return new HttpResponse<>() {
@Override
public int statusCode() {
return statusCode;
}
@Override
public HttpRequest request() {
return null;
}
@Override
public Optional<HttpResponse<String>> previousResponse() {
return Optional.empty();
}
@Override
public HttpHeaders headers() {
return null;
}
@Override
public String body() {
return null;
}
@Override
public Optional<SSLSession> sslSession() {
return Optional.empty();
}
@Override
public URI uri() {
return null;
}
@Override
public HttpClient.Version version() {
return null;
}
};
}
Other attributes (e.g. body, etc.) you could pass as parameters to the method createDummyResponse.
精彩评论