cz.msebera.android.httpclient.HttpStatus Java Examples

The following examples show how to use cz.msebera.android.httpclient.HttpStatus. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HtmlLink.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
 *
 * If the linked content is not already downloaded it triggers a download. Then it stores the response
 * for later use.<br>
 *
 * @param downloadIfNeeded indicates if a request should be performed this hasn't been done previously
 * @param request the request; if null getWebRequest() is called to create one
 * @return {@code null} if no download should be performed and when this wasn't already done; the response
 * received when performing a request for the content referenced by this tag otherwise
 * @throws IOException if an error occurs while downloading the content
 */
public WebResponse getWebResponse(final boolean downloadIfNeeded, WebRequest request) throws IOException {
    if (downloadIfNeeded && cachedWebResponse_ == null) {
        final WebClient webclient = getPage().getWebClient();
        if (null == request) {
            request = getWebRequest();
        }
        try {
            cachedWebResponse_ = webclient.loadWebResponse(request);
            final int statusCode = cachedWebResponse_.getStatusCode();
            final boolean successful = statusCode >= HttpStatus.SC_OK
                                            && statusCode < HttpStatus.SC_MULTIPLE_CHOICES;
            if (successful) {
                executeEvent(Event.TYPE_LOAD);
            }
            else {
                executeEvent(Event.TYPE_ERROR);
            }
        }
        catch (final IOException e) {
            executeEvent(Event.TYPE_ERROR);
            throw e;
        }
    }
    return cachedWebResponse_;
}
 
Example #2
Source File: InstaUtils.java    From Instagram-Profile-Downloader with MIT License 5 votes vote down vote up
public static String login(String username, String pass) throws Exception {
    getInitCookies(ig);

    URLConnection connection = new URL(igAuth).openConnection();
    if(connection instanceof HttpURLConnection){
        HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
        httpURLConnection.setRequestMethod(HttpPost.METHOD_NAME);
        httpURLConnection = addPostHeaders(httpURLConnection);

        String query = new Builder().appendQueryParameter("username", username).appendQueryParameter("password", pass).build().getEncodedQuery();
        OutputStream outputStream = httpURLConnection.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, HTTP.UTF_8));
        bufferedWriter.write(query);
        bufferedWriter.flush();
        bufferedWriter.close();
        outputStream.close();
        httpURLConnection.connect();

        if(httpURLConnection.getResponseCode() != HttpStatus.SC_OK){
            return "bad_request";
        }

        extractAndSetCookies(httpURLConnection);
        JSONObject jsonObject = new JSONObject(buildResultString(httpURLConnection));
        if(jsonObject.get("user").toString().isEmpty()){
            return BuildConfig.VERSION_NAME;
        }

        return jsonObject.get("authenticated").toString();
    }

    throw new IOException("Url is not valid");
}
 
Example #3
Source File: WebClient.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
 *
 * <p>Logs the response's content if its status code indicates a request failure and
 * {@link WebClientOptions#isPrintContentOnFailingStatusCode()} returns {@code true}.
 *
 * @param webResponse the response whose content may be logged
 */
public void printContentIfNecessary(final WebResponse webResponse) {
    if (getOptions().isPrintContentOnFailingStatusCode()) {
        final int statusCode = webResponse.getStatusCode();
        final boolean successful = statusCode >= HttpStatus.SC_OK && statusCode < HttpStatus.SC_MULTIPLE_CHOICES;
        if (!successful) {
            final String contentType = webResponse.getContentType();
            LOG.info("statusCode=[" + statusCode + "] contentType=[" + contentType + "]");
            LOG.info(webResponse.getContentAsString());
        }
    }
}
 
Example #4
Source File: WebClient.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
 *
 * <p>Throws a {@link FailingHttpStatusCodeException} if the request's status code indicates a request
 * failure and {@link WebClientOptions#isThrowExceptionOnFailingStatusCode()} returns {@code true}.
 *
 * @param webResponse the response which may trigger a {@link FailingHttpStatusCodeException}
 */
public void throwFailingHttpStatusCodeExceptionIfNecessary(final WebResponse webResponse) {
    final int statusCode = webResponse.getStatusCode();
    final boolean successful = (statusCode >= HttpStatus.SC_OK && statusCode < HttpStatus.SC_MULTIPLE_CHOICES)
        || statusCode == HttpStatus.SC_USE_PROXY
        || statusCode == HttpStatus.SC_NOT_MODIFIED;
    if (getOptions().isThrowExceptionOnFailingStatusCode() && !successful) {
        throw new FailingHttpStatusCodeException(webResponse);
    }
}
 
Example #5
Source File: WebClient.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
/**
 * <p>Creates a page based on the specified response and inserts it into the specified window. All page
 * initialization and event notification is handled here.</p>
 *
 * <p>Note that if the page created is an attachment page, and an {@link AttachmentHandler} has been
 * registered with this client, the page is <b>not</b> loaded into the specified window; in this case,
 * the page is loaded into a new window, and attachment handling is delegated to the registered
 * <tt>AttachmentHandler</tt>.</p>
 *
 * @param webResponse the response that will be used to create the new page
 * @param webWindow the window that the new page will be placed within
 * @throws IOException if an IO error occurs
 * @throws FailingHttpStatusCodeException if the server returns a failing status code AND the property
 *         {@link WebClientOptions#setThrowExceptionOnFailingStatusCode(boolean)} is set to true
 * @return the newly created page
 * @see #setAttachmentHandler(AttachmentHandler)
 */
public Page loadWebResponseInto(final WebResponse webResponse, final WebWindow webWindow)
    throws IOException, FailingHttpStatusCodeException {

    WebAssert.notNull("webResponse", webResponse);
    WebAssert.notNull("webWindow", webWindow);

    if (webResponse.getStatusCode() == HttpStatus.SC_NO_CONTENT) {
        return webWindow.getEnclosedPage();
    }

    if (webStartHandler_ != null && "application/x-java-jnlp-file".equals(webResponse.getContentType())) {
        webStartHandler_.handleJnlpResponse(webResponse);
        return webWindow.getEnclosedPage();
    }

    if (attachmentHandler_ != null && Attachment.isAttachment(webResponse)) {
        final WebWindow w = openWindow(null, null, webWindow);
        final Page page = pageCreator_.createPage(webResponse, w);
        attachmentHandler_.handleAttachment(page);
        return page;
    }

    final Page oldPage = webWindow.getEnclosedPage();
    if (oldPage != null) {
        // Remove the old windows before create new ones.
        oldPage.cleanUp();
    }
    Page newPage = null;
    if (windows_.contains(webWindow) || getBrowserVersion().hasFeature(WINDOW_EXECUTE_EVENTS)) {
        newPage = pageCreator_.createPage(webResponse, webWindow);

        if (windows_.contains(webWindow)) {
            fireWindowContentChanged(new WebWindowEvent(webWindow, WebWindowEvent.CHANGE, oldPage, newPage));

            // The page being loaded may already have been replaced by another page via JavaScript code.
            if (webWindow.getEnclosedPage() == newPage) {
                newPage.initialize();
                // hack: onload should be fired the same way for all type of pages
                // here is a hack to handle non HTML pages
                if (webWindow instanceof FrameWindow && !newPage.isHtmlPage()) {
                    final FrameWindow fw = (FrameWindow) webWindow;
                    final BaseFrameElement frame = fw.getFrameElement();
                    if (frame.hasEventHandlers("onload")) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Executing onload handler for " + frame);
                        }
                        final Event event = new Event(frame, Event.TYPE_LOAD);
                        ((Node) frame.getScriptableObject()).executeEventLocally(event);
                    }
                }
            }
        }
    }
    return newPage;
}
 
Example #6
Source File: HtmlImage.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
/**
 * <p><span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span></p>
 *
 * <p>Executes this element's <tt>onload</tt> handler if it has one. This method also downloads the image
 * if this element has an <tt>onload</tt> handler (prior to invoking said handler), because applications
 * sometimes use images to send information to the server and use the <tt>onload</tt> handler to get notified
 * when the information has been received by the server.</p>
 *
 * <p>See <a href="http://www.nabble.com/How-should-we-handle-image.onload--tt9850876.html">here</a> and
 * <a href="http://www.nabble.com/Image-Onload-Support-td18895781.html">here</a> for the discussion which
 * lead up to this method.</p>
 *
 * <p>This method may be called multiple times, but will only attempt to execute the <tt>onload</tt>
 * handler the first time it is invoked.</p>
 */
public void doOnLoad() {
    if (onloadInvoked_) {
        return;
    }

    final HtmlPage htmlPage = getHtmlPageOrNull();
    if (htmlPage == null) {
        return; // nothing to do if embedded in XML code
    }

    final WebClient client = htmlPage.getWebClient();
    if (!client.getOptions().isJavaScriptEnabled()) {
        onloadInvoked_ = true;
        return;
    }

    if (hasEventHandlers("onload") && !getSrcAttribute().isEmpty()) {
        onloadInvoked_ = true;
        // An onload handler and source are defined; we need to download the image and then call the onload handler.
        boolean ok;
        try {
            downloadImageIfNeeded();
            final int i = imageWebResponse_.getStatusCode();
            ok = (i >= HttpStatus.SC_OK && i < HttpStatus.SC_MULTIPLE_CHOICES) || i == HttpStatus.SC_USE_PROXY;
        }
        catch (final IOException e) {
            ok = false;
        }
        // If the download was a success, trigger the onload handler.
        if (ok) {
            final Event event = new Event(this, Event.TYPE_LOAD);
            final Node scriptObject = (Node) getScriptableObject();

            final String readyState = htmlPage.getReadyState();
            if (READY_STATE_LOADING.equals(readyState)) {
                final PostponedAction action = new PostponedAction(getPage()) {
                    @Override
                    public void execute() throws Exception {
                        scriptObject.executeEventLocally(event);
                    }
                };
                htmlPage.addAfterLoadAction(action);
            }
            else {
                scriptObject.executeEventLocally(event);
            }
        }
        else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Unable to download image for " + this + "; not firing onload event.");
            }
        }
    }
}
 
Example #7
Source File: HttpUtils.java    From UltimateAndroid with Apache License 2.0 4 votes vote down vote up
public static String getResponseFromGetUrl(String url,
                                               String params) throws Exception {
        Log.d("Chen", "url--" + url);
        if (null != params && !"".equals(params)) {

            url = url + "?";

            String[] paramarray = params.split(",");

            for (int index = 0; null != paramarray && index < paramarray.length; index++) {

                if (index == 0) {

                    url = url + paramarray[index];
                } else {

                    url = url + "&" + paramarray[index];
                }

            }

        }

        HttpGet httpRequest = new HttpGet(url);

//        httpRequest.addHeader("Cookie", logininfo);

        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        int timeoutConnection = 30000;
        HttpConnectionParams.setConnectionTimeout(httpParameters,
                timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 30000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);

        // DefaultHttpClient httpclient = new DefaultHttpClient();
        StringBuffer sb = new StringBuffer();


        try {
            HttpResponse httpResponse = httpclient.execute(httpRequest);

            String inputLine = "";
            // Log.d("Chen","httpResponse.getStatusLine().getStatusCode()"+httpResponse.getStatusLine().getStatusCode());
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                InputStreamReader is = new InputStreamReader(httpResponse
                        .getEntity().getContent());
                BufferedReader in = new BufferedReader(is);
                while ((inputLine = in.readLine()) != null) {

                    sb.append(inputLine);
                }

                in.close();

            } else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        } finally {
            httpclient.getConnectionManager().shutdown();
        }

        return sb.toString();

    }
 
Example #8
Source File: StringWebResponse.java    From HtmlUnit-Android with Apache License 2.0 3 votes vote down vote up
/**
 * Helper method for constructors. Converts the specified string into {@link WebResponseData}
 * with other defaults specified.
 *
 * @param contentString the string to be converted to a <tt>WebResponseData</tt>
 * @return a simple <tt>WebResponseData</tt> with defaults specified
 */
private static WebResponseData getWebResponseData(final String contentString, final Charset charset) {
    final byte[] content = TextUtil.stringToByteArray(contentString, charset);
    final List<NameValuePair> compiledHeaders = new ArrayList<>();
    compiledHeaders.add(new NameValuePair(HttpHeader.CONTENT_TYPE, "text/html; charset=" + charset));
    return new WebResponseData(content, HttpStatus.SC_OK, "OK", compiledHeaders);
}