PlainTextResponseHandler.java 1.0 KB

123456789101112131415161718192021222324252627282930313233
  1. package com.muzhi.zgd.handler;
  2. import com.muzhi.zgd.exception.HttpResponseException;
  3. import com.muzhi.zgd.http.HttpIOUtils;
  4. import com.muzhi.zgd.http.HttpStatus;
  5. import java.io.IOException;
  6. import java.net.HttpURLConnection;
  7. public class PlainTextResponseHandler implements ResponseHandler<String> {
  8. @Override
  9. public void preHandle(HttpURLConnection httpConn) {
  10. httpConn.setConnectTimeout(5000);
  11. httpConn.setReadTimeout(10000);
  12. }
  13. @Override
  14. public String handleResponse(HttpURLConnection httpConn, String charset) throws IOException {
  15. int status = httpConn.getResponseCode();
  16. if (status >= HttpURLConnection.HTTP_OK && status < HttpURLConnection.HTTP_MULT_CHOICE) {
  17. return HttpIOUtils.toInputText(httpConn.getInputStream(), charset);
  18. } else {
  19. String result = HttpIOUtils.toInputText(httpConn.getErrorStream(), charset);
  20. if(result != null && result.length() > 0) {
  21. throw new HttpResponseException(status, result.toString());
  22. }
  23. throw new HttpResponseException(status, HttpStatus.getStatusText(status));
  24. }
  25. }
  26. }