Example usage for org.apache.http.client HttpResponseException HttpResponseException

List of usage examples for org.apache.http.client HttpResponseException HttpResponseException

Introduction

In this page you can find the example usage for org.apache.http.client HttpResponseException HttpResponseException.

Prototype

public HttpResponseException(final int statusCode, final String s) 

Source Link

Usage

From source file:com.pandoroid.pandora.RPC.java

/**
 * Description: This function contacts the remote server with a string
 *    type data package (could be JSON), and returns the remote server's 
 *    response in a string.// w w w.ja va  2 s  .com
 * @throws Exception if url_params or entity_data is empty/null.
 * @throws HttpResponseException if response is not equal HttpStatus.SC_OK
 * @throws IOException if a connection to the remote server can't be made.
 */
public String call(Map<String, String> url_params, String entity_data, boolean require_secure)
        throws Exception, HttpResponseException, IOException {

    if (url_params == null || url_params.size() == 0) {
        throw new Exception("Missing URL paramaters");
    }
    if (entity_data == null) {
        throw new Exception("Missing data for HTTP entity.");
    }

    String full_url;

    if (require_secure) {
        full_url = "https://" + request_url;
    } else {
        full_url = "http://" + request_url;
    }

    HttpPost request = new HttpPost();
    if (user_agent != null) {
        request.addHeader("User-Agent", user_agent);
    }

    URI uri = new URI(full_url.concat(makeUrlParamString(url_params)));
    request.setURI(uri);
    StringEntity entity = null;

    try {
        entity = new StringEntity(entity_data);
        if (entity_type != null) {
            entity.setContentType(entity_type);
        }
    } catch (Exception e) {
        throw new Exception("Pandora RPC Http entity creation error");
    }

    request.setEntity(entity);

    //Send to the server and get our response 
    HttpResponse response = client.execute(request);
    int status_code = response.getStatusLine().getStatusCode();
    if (status_code != HttpStatus.SC_OK) {
        throw new HttpResponseException(status_code,
                "HTTP status code: " + status_code + " != " + HttpStatus.SC_OK);
    }

    //Read the response returned and turn it from a byte stream to a string.
    HttpEntity response_entity = response.getEntity();
    int BUFFER_BYTE_SIZE = 512;
    String ret_data = new String();
    byte[] bytes = new byte[BUFFER_BYTE_SIZE];

    //Check the entity type (usually 'text/plain'). Probably doesn't need
    //to be checked.
    if (response_entity.getContentType().getValue().equals(entity_type)) {
        InputStream content = response_entity.getContent();
        int bytes_read = BUFFER_BYTE_SIZE;

        //Rather than read an arbitrary amount of bytes, lets be sure to get
        //it all.
        while ((bytes_read = content.read(bytes, 0, BUFFER_BYTE_SIZE)) != -1) {
            ret_data += new String(bytes, 0, bytes_read);
        }
    } else {
        throw new Exception(
                "Improper server response entity type: " + response_entity.getContentType().getValue());
    }

    return ret_data;
}

From source file:fi.csc.kapaVirtaAS.VirtaXRoadEndpoint.java

@RequestMapping(value = "/ws", method = RequestMethod.POST)
public ResponseEntity<String> getVirtaResponse(@RequestBody String XRoadRequestMessage) throws Exception {
    FaultMessageService faultMessageService = new FaultMessageService();
    MessageTransformer messageTransformer = new MessageTransformer(conf, faultMessageService);
    VirtaClient virtaClient = new VirtaClient(conf);
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(new MediaType("text", "xml", Charsets.UTF_8));
    HttpResponse virtaResponse;//from  ww  w  .j  a  va2  s.  c om

    try {
        String virtaRequestMessage = messageTransformer.transform(XRoadRequestMessage,
                MessageTransformer.MessageDirection.XRoadToVirta);
        //Send transformed SOAP-request to Virta
        virtaResponse = virtaClient.getVirtaWS(virtaRequestMessage,
                messageTransformer.createAuthenticationString(XRoadRequestMessage));
    } catch (Exception e) {
        log.error(e.toString());
        HttpStatus errorStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        String errorMessage = ERROR_MESSAGE;
        if (e instanceof DOMException) {
            errorStatus = HttpStatus.BAD_REQUEST;
            errorMessage = "Request SOAP-headers did not contain client identifiers (http://x-road.eu/xsd/identifiers)";
        }
        return new ResponseEntity<>(faultMessageService.generateSOAPFault(errorMessage,
                faultMessageService.getReqValidFail(), messageTransformer.getXroadHeaderElement()), httpHeaders,
                errorStatus);
    }

    try {
        if (virtaResponse.getStatusLine().getStatusCode() != 200) {
            log.error(virtaResponse.getStatusLine().getReasonPhrase());
            throw new HttpResponseException(virtaResponse.getStatusLine().getStatusCode(),
                    virtaResponse.getStatusLine().getReasonPhrase());
        }
        BufferedReader rd = new BufferedReader(new InputStreamReader(virtaResponse.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line;
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        String virtaResponseMessage = result.toString();

        return new ResponseEntity<>(messageTransformer.transform(virtaResponseMessage,
                MessageTransformer.MessageDirection.VirtaToXRoad), httpHeaders, HttpStatus.OK);
    } catch (Exception e) {
        log.error(e.toString());
        HttpStatus status = HttpStatus.valueOf(virtaResponse.getStatusLine().getStatusCode());
        if (status.value() == 200) {
            status = HttpStatus.INTERNAL_SERVER_ERROR;
        } else if (IOUtils.toString(virtaResponse.getEntity().getContent()).toLowerCase()
                .contains("access denied")) {
            status = HttpStatus.FORBIDDEN;
        }
        return new ResponseEntity<>(
                faultMessageService.generateSOAPFault(ERROR_MESSAGE + status.name(),
                        faultMessageService.getResValidFail(), messageTransformer.getXroadHeaderElement()),
                httpHeaders, status);
    }
}

From source file:com.hippoapp.asyncmvp.http.AsyncCachedHttpRequest.java

private void makeRequest() throws IOException {
    HttpResponse response = client.execute(request, context);

    StatusLine status = response.getStatusLine();
    if (status.getStatusCode() >= 300) {
        responseHandler.onFailure(protocol,
                new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
    } else {/*from  www .ja  va  2s.  c  o m*/
        byte[] httpResponseByte = EntityUtils.toByteArray(response.getEntity());
        // add to cache
        ResponseData responseData = new ResponseData(status.getStatusCode(), httpResponseByte);
        try {
            AsyncCacheClient.getInstance().put(cacheProtocol, cacheId, responseData);
        } catch (NullPointerException e) {
            // no cache
        }
        responseHandler.onSuccess(protocol, httpResponseByte);
    }
}

From source file:com.puppetlabs.geppetto.forge.client.JSonResponseHandler.java

@Override
public V handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
    StatusLine statusLine = response.getStatusLine();
    int code = statusLine.getStatusCode();
    if (code >= 300) {
        String msg;//  w w  w  .  j av  a 2 s .  c  o  m
        try {
            ErrorResponse errors = parseJson(gson, ForgeHttpClient.getStream(response.getEntity()),
                    ErrorResponse.class);
            if (errors == null)
                msg = statusLine.getReasonPhrase();
            else {
                msg = statusLine.getReasonPhrase() + ": " + errors;
            }
        } catch (Exception e) {
            // Just skip
            msg = statusLine.getReasonPhrase();
        }
        throw new HttpResponseException(statusLine.getStatusCode(), msg);
    }

    HttpEntity entity = response.getEntity();
    if (isOk(code)) {
        if (type == null)
            return null;
        return parseJson(ForgeHttpClient.getStream(entity), type);
    }
    throw createException(ForgeHttpClient.getStream(entity), code, statusLine.getReasonPhrase());
}

From source file:com.hoccer.api.FileCache.java

public void fetch(String locationUri, StreamableContent data)
        throws ClientProtocolException, IOException, Exception {
    HttpGet request = new HttpGet(locationUri);
    HttpResponse response = getHttpClient().execute(request);

    int statuscode = response.getStatusLine().getStatusCode();
    if (statuscode != 200) {
        throw new HttpResponseException(statuscode,
                "Unexpected status code " + statuscode + " while requesting " + locationUri);
    }//from  ww  w  .j a v a2s.c o m

    InputStream is = response.getEntity().getContent();
    OutputStream storageStream = data.openNewOutputStream();
    byte[] buffer = new byte[0xFFFF];
    int len;
    while ((len = is.read(buffer)) != -1) {
        storageStream.write(buffer, 0, len);
    }

    if (data instanceof GenericStreamableContent) {
        Header[] headers = response.getAllHeaders();
        HashMap<String, String> headermap = new HashMap<String, String>();
        for (int i = 0; i < headers.length; i++) {
            headermap.put(headers[i].getName(), headers[i].getValue());
        }
        AsyncHttpRequest.setTypeAndFilename((GenericStreamableContent) data, headermap, locationUri);
    }
}

From source file:com.unifonic.sdk.resources.http.MessagesResourceImpl.java

@Override
public BulkResponse sendBulk(Map<String, String> param) throws IOException {
    OTSRestResponse response = sendRequest(messageUrl.urlSendBulk(), param);
    if (response.getStatusCode() < 400) {
        Type type = new TypeToken<ResponseModel<BulkResponse>>() {
        }.getType();//w w  w .  j  a v a  2 s  .  c o m
        ResponseModel<BulkResponse> respData = GSON.fromJson(response.getData(), type);
        return respData.create();
    } else {
        throw new HttpResponseException(response.getStatusCode(), response.getReasonPhrase());
    }
}

From source file:com.unifonic.sdk.resources.http.EmailResourceImpl.java

@Override
public EmailReportResponse getEmailsReport(Map<String, String> param) throws IOException {
    OTSRestResponse response = sendRequest(emailUrl.urlGetEmailReport(), param);
    if (response.getStatusCode() < 400) {
        Type type = new TypeToken<ResponseModel<EmailReportResponse>>() {
        }.getType();/*from  ww w .  ja v a 2  s.c o  m*/
        ResponseModel<EmailReportResponse> respData = GSON.fromJson(response.getData(), type);
        return respData.create();
    } else if (response.getStatusCode() == 400) {
        EmailReportResponse resp = GSON.fromJson(response.getData(), EmailReportResponse.class);
        return resp;
    } else {
        throw new HttpResponseException(response.getStatusCode(), response.getReasonPhrase());
    }
}

From source file:com.letv.commonjar.http.HttpJsonCallBack.java

@Override
public void handlerResponse(HttpResponse response) throws IOException {
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        byte[] responseBody;
        responseBody = getResponseData(response.getEntity());
        if (!Thread.currentThread().isInterrupted()) {
            if (status.getStatusCode() >= 300) {
                onFailure(status.getStatusCode(),
                        new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
            } else {
                onSuccess(responseBody);
            }/*from w ww .ja va  2s.  c o  m*/
        }
    }
}

From source file:org.kontalk.xmppserver.registration.checkmobi.CheckmobiValidationClient.java

public StatusResult status(String requestId) throws IOException {
    try {/*from w ww .  jav a2  s.c  om*/
        JsonObject data = _status(requestId);
        try {
            boolean validated = data.getAsJsonPrimitive("validated").getAsBoolean();
            return new StatusResult(validated);
        } catch (NullPointerException e) {
            // simulate bad request
            throw new HttpResponseException(400, "Bad request");
        }
    } catch (HttpResponseException e) {
        return new StatusResult(e);
    }
}

From source file:com.unifonic.sdk.resources.http.VerifyResourceImpl.java

@Override
public ResponseModel<Voids> verifyNumber(Map<String, String> map) throws IOException {
    OTSRestResponse otsResponse = sendRequest(verifyUrl.urlVerifyNumber(), map);
    if (otsResponse.getStatusCode() < 400) {
        Type type = new TypeToken<ResponseModel<Voids>>() {
        }.getType();/*from w w w  .  jav a  2 s . co m*/
        ResponseModel<Voids> respData = GSON.fromJson(otsResponse.getData(), type);
        return respData;
    } else if (otsResponse.getStatusCode() == 400) {
        ResponseModel<Voids> respData = GSON.fromJson(otsResponse.getData(), ResponseModel.class);
        return respData;
    } else {
        throw new HttpResponseException(otsResponse.getStatusCode(), otsResponse.getReasonPhrase());
    }
}