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

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

Introduction

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

Prototype

public ClientProtocolException(final Throwable cause) 

Source Link

Usage

From source file:com.helger.peppol.smpclient.SMPHttpResponseHandlerUnsigned.java

@Nonnull
public T handleResponse(@Nonnull final HttpResponse aHttpResponse) throws IOException {
    final StatusLine aStatusLine = aHttpResponse.getStatusLine();
    final HttpEntity aEntity = aHttpResponse.getEntity();
    if (aStatusLine.getStatusCode() >= 300)
        throw new HttpResponseException(aStatusLine.getStatusCode(), aStatusLine.getReasonPhrase());
    if (aEntity == null)
        throw new ClientProtocolException("Response from SMP server contains no content");

    // Read the payload
    final T ret = m_aMarshaller.read(aEntity.getContent());
    if (ret == null)
        throw new ClientProtocolException("Malformed XML document returned from SMP server");
    return ret;/*w  w w.ja v a 2s  . c  o  m*/
}

From source file:com.brett.http.geo.baidu.GeoRequestHttpClient.java

public static JsonNode geoAcquire(String city) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    //    DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
    //    httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
    try {/*from w  w  w .ja v  a  2  s.  c  o m*/

        String address = URLEncoder.encode(city, "utf-8");

        String url = "http://api.map.baidu.com/geocoder/v2/?address={address}&output=json&ak=E4805d16520de693a3fe707cdc962045";

        url = url.replaceFirst("\\{address\\}", address);

        HttpGet httpget = new HttpGet(url);
        httpget.setHeader("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        httpget.setHeader("Accept-Encoding", "gzip, deflate, sdch");
        httpget.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
        httpget.setHeader("Cache-Control", "no-cache");
        httpget.setHeader("Connection", "keep-alive");
        httpget.setHeader("Referer",
                "http://developer.baidu.com/map/index.php?title=webapi/guide/webservice-geocoding");
        httpget.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36");

        System.out.println("Executing request httpget.getRequestLine() " + httpget.getRequestLine());

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity, "utf-8") : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }

        };
        String responseBody = httpclient.execute(httpget, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(HtmlDecoder.decode(responseBody));
        System.out.println(responseBody);

        System.out.println("----------------------------------------");

        ObjectMapper mapper = new ObjectMapper();
        mapper.readValue(responseBody, AddressCoord.class);
        //      JsonNode root = mapper.readTree(responseBody.substring("showLocation&&showLocation(".length(), responseBody.length()-1));

        // {"status":0,"result":{"location":{"lng":116.30783584945,"lat":40.056876296398},"precise":1,"confidence":80,"level":"\u5546\u52a1\u5927\u53a6"}}
        JsonNode root = mapper.readTree(responseBody);

        System.out.println("result : " + city + " = " + root.get("result"));

        return root;

    } finally {
        httpclient.close();
    }
}

From source file:edu.se.ustc.ClientWithResponseHandler.java

public List<BusRouteInfo> run(String URL) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    List<BusRouteInfo> bsrList = new ArrayList<BusRouteInfo>();
    try {//from ww w  .  j a  v  a2s  .com
        HttpGet httpget = new HttpGet(URL);
        //debug
        //System.out.println("Executing request " + httpget.getRequestLine());

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }

        };
        String responseBody = httpclient.execute(httpget, responseHandler);
        //System.out.println("----------------------------------------");

        //System.out.println(responseBody);

        String str = responseBody.substring(responseBody.indexOf("table"), responseBody.lastIndexOf("table"));
        //debug
        //System.out.println(str);

        BusRouteInfo binfo = new BusRouteInfo();
        bsrList = binfo.getBusRouteInfoList(str);

        //debug, print all infomation
        //binfo.printBusRouteInfo(bsrList);

        //select the db
        //dbUtil db = new dbUtil();
        //result=db.executeQuery("SELECT * FROM station_stats");
        //         if(result!=null)
        //             System.out.println(result.getString(1));
    } finally {
        httpclient.close();
    }

    return bsrList;
}

From source file:project.latex.balloon.writer.HttpDataWriter.java

void sendPostRequest(String rawString) throws IOException {
    String jsonString = getJsonStringFromRawData(rawString);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    StringEntity entity = new StringEntity(jsonString, ContentType.create("plain/text", Consts.UTF_8));
    HttpPost httppost = new HttpPost(receiverUrl);
    httppost.addHeader("content-type", "application/json");
    httppost.setEntity(entity);/*from   www  .j a  va  2s. c  o  m*/

    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

        @Override
        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            StatusLine statusLine = response.getStatusLine();
            HttpEntity entity = response.getEntity();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }
            if (entity == null) {
                throw new ClientProtocolException("Response contains no content");
            }
            ContentType contentType = ContentType.getOrDefault(entity);
            Charset charset = contentType.getCharset();
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), charset));
            StringBuilder stringBuilder = new StringBuilder();
            String line = reader.readLine();
            while (line != null) {
                stringBuilder.append(line);
                line = reader.readLine();
            }
            return stringBuilder.toString();
        }
    };

    String responseString = httpclient.execute(httppost, responseHandler);
    logger.info(responseString);
}

From source file:it.av.fac.driver.APIClient.java

public boolean storageRequest(String userToken, JSONObject resource) {
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
        HttpPost httpPost = new HttpPost(endpoint + ADMIN_PATH);

        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("resource", URLEncoder.encode(resource.toString(), "UTF-8")));
        nvps.add(new BasicNameValuePair("token", URLEncoder.encode(userToken, "UTF-8")));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));

        // Create a custom response handler
        ResponseHandler<Boolean> responseHandler = (final HttpResponse response) -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                return status == 200;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }//  www  .  j  a v a2  s.c  o m
        };

        return httpclient.execute(httpPost, responseHandler);
    } catch (IOException ex) {
        Logger.getLogger(APIClient.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
}

From source file:me.ixfan.wechatkit.util.JsonResponseHandler.java

@Override
public JsonObject handleResponse(HttpResponse response) throws IOException {
    StatusLine statusLine = response.getStatusLine();
    HttpEntity entity = response.getEntity();
    if (statusLine.getStatusCode() >= 300) {
        throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
    }// w  w w  . ja v  a2 s.  co m
    if (entity == null) {
        throw new ClientProtocolException("Response contains no content");
    }

    ContentType contentType = ContentType.getOrDefault(entity);
    Charset charset = contentType.getCharset();
    if (null == charset) {
        charset = StandardCharsets.UTF_8;
    }
    Reader reader = new InputStreamReader(entity.getContent(), charset);
    return new JsonParser().parse(reader).getAsJsonObject();
}

From source file:com.unifonic.sdk.HttpSender.java

public OTSRestResponse requestDefault(String url, HttpEntity data) throws IOException {
    HttpPost post = new HttpPost(url);
    post.setEntity(data);//from   w ww  . j  av  a 2s. co  m

    ResponseHandler<OTSRestResponse> rh = new ResponseHandler<OTSRestResponse>() {
        @Override
        public OTSRestResponse handleResponse(HttpResponse response)
                throws ClientProtocolException, IOException {
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                throw new ClientProtocolException("Response contains no content");
            }
            OTSRestResponse orr = new OTSRestResponse();
            orr.setStatusCode(response.getStatusLine().getStatusCode());
            orr.setReasonPhrase(response.getStatusLine().getReasonPhrase());
            String respContent = InputStreamUtil.readString(entity.getContent());
            log.debug("Response:" + orr.getStatusCode() + ":" + orr.getReasonPhrase() + ":" + respContent);
            if (orr.getStatusCode() == 400) {
                respContent = respContent.replace(",\"data\":[]", "");
            }
            orr.setData(respContent);
            return orr;
        }
    };
    OTSRestResponse execute = httpClient.execute(post, rh);
    return execute;
}

From source file:com.opensearchserver.affinities.process.AffinityProcess.java

/**
 * @param server/*  www  .j av a  2 s. c  o  m*/
 * @return the right AffinityProcess implementation
 * @throws IOException
 */
private static AffinityProcessInterface checkServerResource(ServerResource server) throws IOException {
    if (server == null)
        throw new ClientProtocolException("The server to used has not been configured.");
    switch (server.getVersionOfDefault()) {
    case 1:
        return new AffinityProcess1Impl();
    case 2:
        return new AffinityProcess2Impl();
    }
    throw new JsonApplicationException(Status.BAD_REQUEST, "Version not supported: " + server.version);
}

From source file:com.quartzdesk.executor.core.job.UrlInvokerJob.java

@Override
protected void executeJob(final JobExecutionContext context) throws JobExecutionException {
    log.debug("Inside job: {}", context.getJobDetail().getKey());
    JobDataMap jobDataMap = context.getMergedJobDataMap();

    // url (required)
    final String url = jobDataMap.getString(JDM_KEY_URL);
    if (url == null) {
        throw new JobExecutionException("Missing required '" + JDM_KEY_URL + "' job data map parameter.");
    }//from   w w w  . j  a  v a2 s.c  o m

    // username (optional)
    String username = jobDataMap.getString(JDM_KEY_USERNAME);
    // password (optional)
    String password = jobDataMap.getString(JDM_KEY_PASSWORD);

    CloseableHttpClient httpClient;
    if (username != null && password != null) {
        // use HTTP basic authentication
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

        httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    } else {
        // use no HTTP authentication
        httpClient = HttpClients.custom().build();
    }

    try {
        HttpPost httpPost = new HttpPost(url);

        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse httpResponse) throws IOException {
                int status = httpResponse.getStatusLine().getStatusCode();

                //context.setResult( Integer.toString( status ) );

                if (status >= 200 && status < 300) {
                    HttpEntity entity = httpResponse.getEntity();
                    return entity == null ? null : EntityUtils.toString(entity);
                } else {
                    throw new ClientProtocolException(
                            "URL: " + url + " returned unexpected response status code: " + status);
                }
            }
        };

        log.debug("HTTP request line: {}", httpPost.getRequestLine());

        log.info("Invoking target URL: {}", url);
        String responseText = httpClient.execute(httpPost, responseHandler);

        log.debug("Response text: {}", responseText);

        if (!responseText.trim().isEmpty()) {
            /*
             * We use the HTTP response text as the Quartz job execution result. This code can then be easily
             * viewed in the Execution History in the QuartzDesk GUI and it can be, for example, used to trigger
             * execution notifications.
             */
            context.setResult(responseText);
        }

    } catch (IOException e) {
        throw new JobExecutionException("Error invoking URL: " + url, e);
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            log.error("Error closing HTTP client.", e);
        }
    }
}

From source file:org.eclipse.lyo.testsuite.server.trsutils.RDFModelResponseHandler.java

@Override
public Model handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
    authTypes = response.getHeaders("WWW-Authenticate");
    statusCode = response.getStatusLine().getStatusCode();
    reason = response.getStatusLine().getReasonPhrase();
    Model model = ModelUtil.createDefaultModel();
    HttpEntity entity = response.getEntity();
    try {/*from w ww.  ja v a2  s.c o m*/
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            HttpErrorHandler.responseToException(response);
        }

        if (entity == null)

            throw new InvalidRDFResourceException(
                    MessageFormat.format(Messages.getServerString("rdf.model.response.helper.missing.rdf"), //$NON-NLS-1$
                            base.getURI()));

        String rdfFormat = null;
        final Header contentTypeHeader = response.getFirstHeader(HttpConstants.CONTENT_TYPE);
        if (contentTypeHeader != null) {
            final ContentType contentType = ContentType.parse(contentTypeHeader.getValue());
            if (contentType != null) {
                Lang lang = WebContent.contentTypeToLang(contentType.getContentType());
                if (lang != null) {
                    rdfFormat = lang.getName();
                } else if (HttpConstants.CT_TEXT_XML.equals(contentType.getContentType())) {
                    rdfFormat = Lang.RDFXML.getName(); // attempt RDF
                    // parsing anyway
                }
            }
        }

        if (rdfFormat == null)
            throw new ClientProtocolException(
                    MessageFormat.format(Messages.getServerString("rdf.model.response.helper.bad.content.type"), //$NON-NLS-1$
                            base.getURI()));

        String content = EntityUtils.toString(entity, HTTP.UTF_8);
        try {
            model.read(new StringReader(content), base.getURI(), rdfFormat);
        } catch (Exception e) {
            if (e.getMessage().contains("Interrupt") //$NON-NLS-1$
                    || Thread.currentThread().isInterrupted()) {
                Thread.currentThread().interrupt();
                throw (IOException) new IOException().initCause(e);
            }

            throw new InvalidRDFResourceException(
                    MessageFormat.format(Messages.getServerString("rdf.model.response.helper.unparseable.rdf"), //$NON-NLS-1$
                            base.getURI(), content),
                    e);
        }

        HttpResponseUtil.finalize(response);
    } finally {
        try {
            if (entity != null) {
                EntityUtils.consume(entity);
            }
        } catch (IOException e) {
            // ignore
        }
    }
    return model;
}