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;
}
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());
}
});
}
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());
}
});
}
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());
}
}
}
}
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();
}
}
}
Aggregations