Search in sources :

Example 41 with StatusLine

use of org.apache.http.StatusLine in project saga-android by AnandChowdhary.

the class HurlStack method performRequest.

@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);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(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()) {
        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) {
        // 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);
        }
    }
    return response;
}
Also used : HashMap(java.util.HashMap) IOException(java.io.IOException) ProtocolVersion(org.apache.http.ProtocolVersion) URL(java.net.URL) BasicStatusLine(org.apache.http.message.BasicStatusLine) BasicStatusLine(org.apache.http.message.BasicStatusLine) StatusLine(org.apache.http.StatusLine) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpURLConnection(java.net.HttpURLConnection) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) List(java.util.List) BasicHeader(org.apache.http.message.BasicHeader)

Example 42 with StatusLine

use of org.apache.http.StatusLine in project intellij-community by JetBrains.

the class CCStepicConnector method postTask.

public static void postTask(final Project project, @NotNull final Task task, final int lessonId) {
    final HttpPost request = new HttpPost(EduStepicNames.STEPIC_API_URL + "/step-sources");
    final Gson gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().registerTypeAdapter(AnswerPlaceholder.class, new StudySerializationUtils.Json.StepicAnswerPlaceholderAdapter()).create();
    ApplicationManager.getApplication().invokeLater(() -> {
        final String requestBody = gson.toJson(new StepicWrappers.StepSourceWrapper(project, task, lessonId));
        request.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));
        try {
            final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient();
            if (client == null)
                return;
            final CloseableHttpResponse response = client.execute(request);
            final StatusLine line = response.getStatusLine();
            final HttpEntity responseEntity = response.getEntity();
            final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
            EntityUtils.consume(responseEntity);
            if (line.getStatusCode() != HttpStatus.SC_CREATED) {
                LOG.error("Failed to push " + responseString);
                return;
            }
            final JsonObject postedTask = new Gson().fromJson(responseString, JsonObject.class);
            final JsonObject stepSource = postedTask.getAsJsonArray("step-sources").get(0).getAsJsonObject();
            task.setStepId(stepSource.getAsJsonPrimitive("id").getAsInt());
        } catch (IOException e) {
            LOG.error(e.getMessage());
        }
    });
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpEntity(org.apache.http.HttpEntity) GsonBuilder(com.google.gson.GsonBuilder) StudySerializationUtils(com.jetbrains.edu.learning.StudySerializationUtils) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) StatusLine(org.apache.http.StatusLine) StringEntity(org.apache.http.entity.StringEntity) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Example 43 with StatusLine

use of org.apache.http.StatusLine in project intellij-community by JetBrains.

the class CCStepicConnector method deleteTask.

public static void deleteTask(@NotNull final Integer task) {
    final HttpDelete request = new HttpDelete(EduStepicNames.STEPIC_API_URL + EduStepicNames.STEP_SOURCES + task);
    ApplicationManager.getApplication().invokeLater(() -> {
        try {
            final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient();
            if (client == null)
                return;
            final CloseableHttpResponse response = client.execute(request);
            final HttpEntity responseEntity = response.getEntity();
            final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
            EntityUtils.consume(responseEntity);
            final StatusLine line = response.getStatusLine();
            if (line.getStatusCode() != HttpStatus.SC_NO_CONTENT) {
                LOG.error("Failed to delete task " + responseString);
            }
        } catch (IOException e) {
            LOG.error(e.getMessage());
        }
    });
}
Also used : StatusLine(org.apache.http.StatusLine) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpDelete(org.apache.http.client.methods.HttpDelete) HttpEntity(org.apache.http.HttpEntity) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) IOException(java.io.IOException)

Example 44 with StatusLine

use of org.apache.http.StatusLine in project SeaStar by 13120241790.

the class BreakpointHttpResponseHandler method sendResponseMessage.

@Override
public void sendResponseMessage(HttpResponse response) {
    if (!Thread.currentThread().isInterrupted() && !interrupt) {
        Throwable error = null;
        InputStream instream = null;
        StatusLine status = response.getStatusLine();
        HttpEntity entity = response.getEntity();
        try {
            if (entity == null) {
                throw new IOException("Fail download. entity is null.");
            }
            // 处理contentLength
            long contentLength = entity.getContentLength();
            if (contentLength == -1) {
                contentLength = entity.getContent().available();
            }
            //如果临时文件存在,得到之前下载的大小
            if (tempFile.exists()) {
                previousFileSize = tempFile.length();
            }
            // 得到总大小,包括之前已经下载的
            totalSize = contentLength + previousFileSize;
            if (targetFile.exists() && totalSize == targetFile.length()) {
                NLog.e(tag, "Output file already exists. Skipping download.");
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), "success".getBytes());
                return;
            }
            //获取当前下载文件流
            instream = entity.getContent();
            if (instream == null) {
                throw new IOException("Fail download. instream is null.");
            }
            randomAccessFile = new RandomAccessFile(tempFile, "rw");
            randomAccessFile.seek(randomAccessFile.length());
            byte[] buffer = new byte[BUFFER_SIZE];
            int length, count = 0;
            while ((length = instream.read(buffer)) != -1 && !Thread.currentThread().isInterrupted() && !interrupt) {
                count += length;
                downloadSize = count + previousFileSize;
                randomAccessFile.write(buffer, 0, length);
                sendProgressMessage((int) downloadSize, (int) totalSize);
            }
            //判断下载大小与总大小不一致
            if (!Thread.currentThread().isInterrupted() && !interrupt) {
                if (downloadSize != totalSize && totalSize != -1) {
                    throw new IOException("Fail download. totalSize not eq downloadSize.");
                }
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
            error = e;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            error = e;
        } catch (IOException e) {
            e.printStackTrace();
            error = e;
        } finally {
            try {
                if (instream != null)
                    instream.close();
                if (randomAccessFile != null)
                    randomAccessFile.close();
            } catch (IOException e) {
                e.printStackTrace();
                error = e;
            }
        }
        // additional cancellation check as getResponseData() can take non-zero time to process
        if (!Thread.currentThread().isInterrupted() && !interrupt) {
            if (status.getStatusCode() >= 300 || error != null) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), error.getMessage().getBytes(), new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
            } else {
                tempFile.renameTo(targetFile);
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), "success".getBytes());
            }
        }
    }
}
Also used : StatusLine(org.apache.http.StatusLine) HttpEntity(org.apache.http.HttpEntity) RandomAccessFile(java.io.RandomAccessFile) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException)

Example 45 with StatusLine

use of org.apache.http.StatusLine in project infoarchive-sip-sdk by Enterprise-Content-Management.

the class ApacheHttpClient method execute.

@SuppressWarnings("PMD.AvoidRethrowingException")
protected <T> T execute(HttpRequestBase request, ResponseFactory<T> factory) throws IOException {
    CloseableHttpResponse httpResponse;
    try {
        httpResponse = client.execute(request);
    } catch (HttpResponseException e) {
        throw new HttpException(e.getStatusCode(), e);
    } catch (HttpException e) {
        throw e;
    } catch (IOException e) {
        throw new HttpException(500, e);
    }
    Runnable closeResponse = () -> {
        IOUtils.closeQuietly(httpResponse);
        request.releaseConnection();
    };
    boolean shouldCloseResponse = true;
    try {
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (!isOk(statusCode)) {
            HttpEntity entity = httpResponse.getEntity();
            String body = toString(entity);
            String method = request.getMethod();
            URI uri = request.getURI();
            String reasonPhrase = statusLine.getReasonPhrase();
            throw new HttpException(statusCode, String.format("%n%s %s%n==> %d %s%n%s", method, uri, statusCode, reasonPhrase, body));
        }
        T result = factory.create(new ApacheResponse(httpResponse), closeResponse);
        shouldCloseResponse = false;
        return result;
    } catch (IOException e) {
        throw new RuntimeIoException(e);
    } finally {
        if (shouldCloseResponse) {
            closeResponse.run();
        }
    }
}
Also used : HttpEntity(org.apache.http.HttpEntity) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) URI(java.net.URI) RuntimeIoException(com.opentext.ia.sdk.support.io.RuntimeIoException) StatusLine(org.apache.http.StatusLine)

Aggregations

StatusLine (org.apache.http.StatusLine)193 IOException (java.io.IOException)83 HttpResponse (org.apache.http.HttpResponse)76 HttpEntity (org.apache.http.HttpEntity)61 BasicStatusLine (org.apache.http.message.BasicStatusLine)46 ProtocolVersion (org.apache.http.ProtocolVersion)42 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)40 HttpGet (org.apache.http.client.methods.HttpGet)38 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)37 Header (org.apache.http.Header)36 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)34 Test (org.junit.Test)31 HttpPost (org.apache.http.client.methods.HttpPost)26 HashMap (java.util.HashMap)23 HttpResponseException (org.apache.http.client.HttpResponseException)23 StringEntity (org.apache.http.entity.StringEntity)23 URL (java.net.URL)20 BasicHeader (org.apache.http.message.BasicHeader)16 HttpURLConnection (java.net.HttpURLConnection)15 List (java.util.List)15