Example usage for org.apache.http.message BasicHttpResponse getStatusLine

List of usage examples for org.apache.http.message BasicHttpResponse getStatusLine

Introduction

In this page you can find the example usage for org.apache.http.message BasicHttpResponse getStatusLine.

Prototype

public StatusLine getStatusLine() 

Source Link

Usage

From source file:org.dhis.smssync.net.MainHttpClient.java

/**
 * Upload SMS to a web service via HTTP POST
 * // w ww.ja  va2 s.c om
 * @param address
 * @throws MalformedURLException
 * @throws IOException
 * @return
 */
public static boolean postSmsToWebService(String url, String xml, Context context) {

    Prefrences.loadPreferences(context);
    String encoding = Prefrences.dhisLoginPref;

    // Create a new HttpClient and Post Header
    HttpPost httppost = new HttpPost(url);
    httppost.setHeader("Authorization", "Basic " + encoding);

    try {
        StringEntity se = new StringEntity(xml, HTTP.UTF_8);

        se.setContentType("application/xml");
        httppost.setEntity(se);

        BasicHttpResponse response = (BasicHttpResponse) httpclient.execute(httppost);

        Log.i(CLASS_TAG, "postSmsToWebService(): code: " + response.getStatusLine().getStatusCode() + " xml: "
                + xml + " encoding: " + encoding);

        if (response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300) {
            return true;
        } else {
            return false;
        }

    } catch (ClientProtocolException e) {
        return false;
    } catch (IOException e) {
        return false;
    }
}

From source file:ch.scythe.hsr.api.TimeTableAPI.java

public boolean validateCredentials(String login, String password) throws ServerConnectionException {
    boolean result = false;
    try {/*from  w ww .  j av a 2 s  .c om*/
        HttpGet get = createHttpGet(URL + METHOD_GET_TIMEPERIOD, login, password);
        HttpClient httpclient = new DefaultHttpClient();

        BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient.execute(get);
        int httpStatus = httpResponse.getStatusLine().getStatusCode();

        result = HttpStatus.SC_OK == httpStatus;

    } catch (Exception e) {
        throw new ServerConnectionException(e);
    }

    return result;
}

From source file:org.apache.hadoop.gateway.rm.dispatch.RMHaDispatchTest.java

@Test
public void testConnectivityFailover() throws Exception {
    String serviceName = "RESOURCEMANAGER";
    HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
    descriptor.addServiceConfig(//from  w  w  w. ja  va  2 s .  c o  m
            HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000", null, null));
    HaProvider provider = new DefaultHaProvider(descriptor);
    URI uri1 = new URI("http://passive-host");
    URI uri2 = new URI("http://other-host");
    URI uri3 = new URI("http://active-host");
    ArrayList<String> urlList = new ArrayList<>();
    urlList.add(uri1.toString());
    urlList.add(uri2.toString());
    urlList.add(uri3.toString());
    provider.addHaService(serviceName, urlList);
    FilterConfig filterConfig = EasyMock.createNiceMock(FilterConfig.class);
    ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);

    EasyMock.expect(filterConfig.getServletContext()).andReturn(servletContext).anyTimes();
    EasyMock.expect(servletContext.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME))
            .andReturn(provider).anyTimes();

    BasicHttpResponse inboundResponse = EasyMock.createNiceMock(BasicHttpResponse.class);
    EasyMock.expect(inboundResponse.getStatusLine()).andReturn(getStatusLine()).anyTimes();
    EasyMock.expect(inboundResponse.getEntity()).andReturn(getResponseEntity()).anyTimes();
    EasyMock.expect(inboundResponse.getFirstHeader(LOCATION)).andReturn(getFirstHeader(uri3.toString()))
            .anyTimes();

    BasicHttpParams params = new BasicHttpParams();

    HttpUriRequest outboundRequest = EasyMock.createNiceMock(HttpRequestBase.class);
    EasyMock.expect(outboundRequest.getMethod()).andReturn("GET").anyTimes();
    EasyMock.expect(outboundRequest.getURI()).andReturn(uri1).anyTimes();
    EasyMock.expect(outboundRequest.getParams()).andReturn(params).anyTimes();

    HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(inboundRequest.getRequestURL()).andReturn(new StringBuffer(uri2.toString())).once();
    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(0))
            .once();
    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(1))
            .once();

    HttpServletResponse outboundResponse = EasyMock.createNiceMock(HttpServletResponse.class);
    EasyMock.expect(outboundResponse.getOutputStream()).andAnswer(new IAnswer<ServletOutputStream>() {
        @Override
        public ServletOutputStream answer() throws Throwable {
            return new ServletOutputStream() {
                @Override
                public void write(int b) throws IOException {
                    throw new IOException("unreachable-host");
                }

                @Override
                public void setWriteListener(WriteListener arg0) {
                }

                @Override
                public boolean isReady() {
                    return false;
                }
            };
        }
    }).once();
    Assert.assertEquals(uri1.toString(), provider.getActiveURL(serviceName));
    EasyMock.replay(filterConfig, servletContext, inboundResponse, outboundRequest, inboundRequest,
            outboundResponse);

    RMHaDispatch dispatch = new RMHaDispatch();
    dispatch.setHttpClient(new DefaultHttpClient());
    dispatch.setHaProvider(provider);
    dispatch.init();
    long startTime = System.currentTimeMillis();
    try {
        dispatch.setInboundResponse(inboundResponse);
        dispatch.executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } catch (IOException e) {
        //this is expected after the failover limit is reached
    }
    Assert.assertEquals(uri3.toString(),
            dispatch.getUriFromInbound(inboundRequest, inboundResponse, null).toString());
    long elapsedTime = System.currentTimeMillis() - startTime;
    Assert.assertEquals(uri3.toString(), provider.getActiveURL(serviceName));
    //test to make sure the sleep took place
    Assert.assertTrue(elapsedTime > 1000);
}

From source file:ch.scythe.hsr.api.TimeTableAPI.java

private void updateCache(String dateString, Date cacheTimestamp, String login, String password)
        throws RequestException, ServerConnectionException, ResponseParseException, AccessDeniedException {

    Log.i(LOGGING_TAG, "Starting to read data from the server.");
    long before = System.currentTimeMillis();

    try {//from   ww  w .  ja v a  2 s.c  om

        HttpGet get = createHttpGet(URL + METHOD_GET_TIMETABLE + login, login, password);
        HttpClient httpclient = new DefaultHttpClient();

        BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient.execute(get);
        InputStream jsonStream = null;
        int httpStatus = httpResponse.getStatusLine().getStatusCode();
        if (httpStatus == HttpStatus.SC_OK) {
            jsonStream = httpResponse.getEntity().getContent();
        } else if (httpStatus == HttpStatus.SC_UNAUTHORIZED) {
            throw new AccessDeniedException();
        } else {
            throw new RequestException("Request not successful. \nHTTP Status: " + httpStatus);
        }

        Log.i(LOGGING_TAG, "Finished reading from server.");

        // convert JSON to Java objects
        JsonTimetableWeek serverData = new GsonParser().parse(jsonStream);
        UiWeek uiWeek = DataAssembler.convert(serverData);

        // open streams to cache the files
        DataOutputStream cacheTimestampOutputStream = new DataOutputStream(
                context.openFileOutput(TIMETABLE_CACHE_TIMESTAMP, Context.MODE_PRIVATE));
        FileOutputStream xmlCacheOutputStream = context.openFileOutput(TIMETABLE_CACHE_SERIALIZED,
                Context.MODE_PRIVATE);

        // write data to streams
        ObjectOutputStream out = new ObjectOutputStream(xmlCacheOutputStream);
        out.writeObject(uiWeek);
        cacheTimestampOutputStream.writeLong(new Date().getTime());

        safeCloseStream(xmlCacheOutputStream);
        safeCloseStream(cacheTimestampOutputStream);

    } catch (UnsupportedEncodingException e) {
        throw new RequestException(e);
    } catch (IllegalStateException e) {
        throw new RequestException(e);
    } catch (IOException e) {
        throw new ServerConnectionException(e);
    }

    Log.i(LOGGING_TAG,
            "Read and parsed data from the server in " + (System.currentTimeMillis() - before) + "ms.");
}

From source file:com.kubeiwu.commontool.khttp.toolbox.HurlStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());//
    map.putAll(additionalHeaders);// w ww  .  j  a v  a 2  s. c o m
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);// ?url
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);

    for (String headerName : map.keySet()) {// header
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could
        // not be retrieved.
        // Signal to the caller that something was wrong with the
        // connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(),
            connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            // Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            // response.addHeader(h);
            //cookie?
            String key = header.getKey();
            List<String> values = header.getValue();
            if (key.equalsIgnoreCase("set-cookie")) {
                StringBuilder cookieString = new StringBuilder();
                for (String value : values) {
                    cookieString.append(value).append("\n");// \ncookie??
                }
                cookieString.deleteCharAt(cookieString.length() - 1);
                Header h = new BasicHeader(header.getKey(), cookieString.toString());
                response.addHeader(h);
            } else {
                Header h = new BasicHeader(header.getKey(), values.get(0));
                response.addHeader(h);
            }
        }
    }
    System.out.println("performRequest---999999-getStatusLine=" + response.getStatusLine());
    return response;
}

From source file:water.ga.GoogleAnalytics.java

@SuppressWarnings({ "rawtypes" })
public GoogleAnalyticsResponse post(GoogleAnalyticsRequest request) {
    GoogleAnalyticsResponse response = new GoogleAnalyticsResponse();
    if (!config.isEnabled()) {
        return response;
    }/*from   w w w . ja  v a2s  .com*/

    BasicHttpResponse httpResponse = null;
    try {
        List<NameValuePair> postParms = new ArrayList<NameValuePair>();

        //Log.debug("GA Processing " + request);

        //Process the parameters
        processParameters(request, postParms);

        //Process custom dimensions
        processCustomDimensionParameters(request, postParms);

        //Process custom metrics
        processCustomMetricParameters(request, postParms);

        //Log.debug("GA Processed all parameters and sending the request " + postParms);

        HttpPost httpPost = new HttpPost(config.getUrl());
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(postParms, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            Log.warn("This systems doesn't support UTF-8!");
        }

        try {
            httpResponse = (BasicHttpResponse) httpClient.execute(httpPost);
        } catch (ClientProtocolException e) {
            //Log.trace("GA connectivity had a problem or the connectivity was aborted.  "+e.toString());
        } catch (IOException e) {
            //Log.trace("GA connectivity suffered a protocol error.  "+e.toString());
        }

        //Log.debug("GA response: " +httpResponse.toString());
        response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
        response.setPostedParms(postParms);

        try {
            EntityUtils.consume(httpResponse.getEntity());
        } catch (IOException e) {
            /*consume quietly*/}

        if (config.isGatherStats()) {
            gatherStats(request);
        }

    } catch (Exception e) {
        if (e instanceof UnknownHostException) {
            //Log.trace("Coudln't connect to GA. Internet may not be available. " + e.toString());
        } else {
            //Log.trace("Exception while sending the GA tracker request: " + request +".  "+ e.toString());
        }
    }

    return response;
}

From source file:ste.web.http.handlers.BugFreeFileHandler.java

@Test
public void mime_type_based_on_file_extension() throws Exception {
    FileHandler h = new FileHandler("src/test/mime");

    BasicHttpRequest request = HttpUtils.getSimpleGet("/test.txt");
    BasicHttpResponse response = HttpUtils.getBasicResponse();

    h.handle(request, response, new HttpSessionContext());

    then(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK);
    then(response.getEntity().getContentType().getValue()).isEqualTo(ContentType.TEXT_PLAIN.getMimeType());

    request = HttpUtils.getSimpleGet("/test.html");
    h.handle(request, response, new HttpSessionContext());
    then(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK);
    then(response.getEntity().getContentType().getValue()).isEqualTo(ContentType.TEXT_HTML.getMimeType());

    request = HttpUtils.getSimpleGet("/test.png");
    h.handle(request, response, new HttpSessionContext());
    then(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK);
    then(response.getEntity().getContentType().getValue())
            .isEqualTo(ContentType.create("image/png").getMimeType());
}

From source file:ste.web.http.handlers.BugFreeFileHandler.java

@Test
public void default_mime_type_is_octet_binary() throws Exception {
    FileHandler h = new FileHandler("src/test/mime");

    BasicHttpRequest request = HttpUtils.getSimpleGet("/test.bin");
    BasicHttpResponse response = HttpUtils.getBasicResponse();

    h.handle(request, response, new HttpSessionContext());

    then(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK);
    then(response.getEntity().getContentType().getValue())
            .isEqualTo(ContentType.APPLICATION_OCTET_STREAM.getMimeType());
}

From source file:ste.web.http.handlers.BugFreeFileHandler.java

@Test
public void not_found() throws Exception {
    FileHandler h = new FileHandler("src/test/mime");

    BasicHttpRequest request = HttpUtils.getSimpleGet("/none.bin");
    BasicHttpResponse response = HttpUtils.getBasicResponse();

    h.handle(request, response, new HttpSessionContext());

    then(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_NOT_FOUND);
    then(IOUtils.toString(response.getEntity().getContent())).contains("/none.bin");
}