List of usage examples for org.apache.http.client ResponseHandler ResponseHandler
ResponseHandler
From source file:com.springsource.insight.plugin.apache.http.hc4.HttpClientExecutionCollectionAspectTest.java
private void runResponseHandlerTest(String testName, HttpHost host, HttpContext context) throws IOException { HttpClient httpClient = new DefaultHttpClient(); String uri = createTestUri(testName); HttpGet request = new HttpGet(uri); // must be final or the anonymous class cannot reference it... final AtomicReference<HttpResponse> rspRef = new AtomicReference<HttpResponse>(null); ResponseHandler<HttpResponse> handler = new ResponseHandler<HttpResponse>() { public HttpResponse handleResponse(HttpResponse response) throws ClientProtocolException, IOException { HttpResponse prevValue = rspRef.getAndSet(response); assertNull("Duplicate response handling", prevValue); return response; }/*from w w w . ja v a2 s .c o m*/ }; HttpResponse response; if (host == null) { response = (context == null) ? httpClient.execute(request, handler) : httpClient.execute(request, handler, context); } else { response = (context == null) ? httpClient.execute(host, request, handler) : httpClient.execute(host, request, handler, context); } assertSame("Mismatched reference and return value", response, rspRef.get()); handleResponse(testName, uri, request, response, true); }
From source file:net.ymate.framework.commons.HttpClientHelper.java
public IHttpResponse post(String url, ContentType contentType, InputStream content, Header[] headers, final String defaultResponseCharset) throws Exception { CloseableHttpClient _httpClient = __doBuildHttpClient(); try {/*from w ww . j av a2 s. c om*/ RequestBuilder _reqBuilder = RequestBuilder.post().setUri(url).setEntity(EntityBuilder.create() .setContentEncoding(contentType == null || contentType.getCharset() == null ? DEFAULT_CHARSET : contentType.getCharset().name()) .setContentType(contentType).setStream(content).build()); if (headers != null && headers.length > 0) { for (Header _header : headers) { _reqBuilder.addHeader(_header); } } return _httpClient.execute(_reqBuilder.build(), new ResponseHandler<IHttpResponse>() { public IHttpResponse handleResponse(HttpResponse response) throws IOException { if (StringUtils.isNotBlank(defaultResponseCharset)) { return new IHttpResponse.NEW(response, defaultResponseCharset); } return new IHttpResponse.NEW(response); } }); } finally { _httpClient.close(); } }
From source file:it.anyplace.sync.httprelay.client.HttpRelayConnection.java
private HttpRelayProtos.HttpRelayServerMessage sendMessage( HttpRelayProtos.HttpRelayPeerMessage.Builder peerMessageBuilder) { try {// www . ja v a2s.c o m if (!Strings.isNullOrEmpty(sessionId)) { peerMessageBuilder.setSessionId(sessionId); } logger.debug("send http relay peer message = {} session id = {} sequence = {}", peerMessageBuilder.getMessageType(), peerMessageBuilder.getSessionId(), peerMessageBuilder.getSequence()); HttpClient httpClient = HttpClients.custom() // .setSSLSocketFactory(new SSLConnectionSocketFactory(new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)) .build(); HttpPost httpPost = new HttpPost(httpRelayServerUrl); httpPost.setEntity(new ByteArrayEntity(peerMessageBuilder.build().toByteArray())); final HttpRelayProtos.HttpRelayServerMessage serverMessage = httpClient.execute(httpPost, new ResponseHandler<HttpRelayProtos.HttpRelayServerMessage>() { @Override public HttpRelayProtos.HttpRelayServerMessage handleResponse(HttpResponse response) throws ClientProtocolException, IOException { checkArgument(equal(response.getStatusLine().getStatusCode(), HttpStatus.SC_OK), "http error %s", response.getStatusLine()); return HttpRelayProtos.HttpRelayServerMessage .parseFrom(EntityUtils.toByteArray(response.getEntity())); } }); logger.debug("received http relay server message = {}", serverMessage.getMessageType()); checkArgument(!equal(serverMessage.getMessageType(), HttpRelayProtos.HttpRelayServerMessageType.ERROR), "server error : %s", new Object() { @Override public String toString() { return serverMessage.getData().toStringUtf8(); } }); return serverMessage; } catch (IOException ex) { throw new RuntimeException(ex); } }
From source file:org.apache.marmotta.client.clients.ResourceClient.java
/** * Update the content of the resource identified by the URI given as argument. The resource has to exist before * content can be uploaded to it. Any existing content will be overridden. The stream of the content object * will be consumed by this method. Throws ContentFormatException if the content type is not supported, * NotFoundException if the resource does not exist. * @param uri//w w w .ja v a 2s . c om * @param content * @throws IOException * @throws MarmottaClientException */ public void updateResourceContent(final String uri, final Content content) throws IOException, MarmottaClientException { HttpClient httpClient = HTTPUtil.createClient(config); HttpPut put = new HttpPut(getServiceUrl(uri)); put.setHeader("Content-Type", content.getMimeType() + "; rel=content"); ContentProducer cp = new ContentProducer() { @Override public void writeTo(OutputStream outstream) throws IOException { ByteStreams.copy(content.getStream(), outstream); } }; put.setEntity(new EntityTemplate(cp)); ResponseHandler<Boolean> handler = new ResponseHandler<Boolean>() { @Override public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException { EntityUtils.consume(response.getEntity()); switch (response.getStatusLine().getStatusCode()) { case 200: log.debug("content for resource {} updated", uri); return true; case 406: log.error("server does not support content type {} for resource {}, cannot update", content.getMimeType(), uri); return false; case 404: log.error("resource {} does not exist, cannot update", uri); return false; default: log.error("error updating resource {}: {} {}", new Object[] { uri, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase() }); return false; } } }; try { httpClient.execute(put, handler); } catch (IOException ex) { put.abort(); throw ex; } finally { put.releaseConnection(); } }
From source file:org.jets3t.service.utils.oauth.OAuthUtils.java
/** * Performs an HTTP/S POST request to a given URL with the given POST parameters * and parses the response document, which must be JSON, into a Map of name/value objects. * * @param endpointUri Authorization or token endpoint * @param postParams Name value pairs//ww w.j a v a 2s . c o m * @return JSON mapped response * @throws ClientProtocolException No HTTP 200 response * @throws IOException */ protected Map<String, Object> performPostRequestAndParseJSONResponse(String endpointUri, List<NameValuePair> postParams) throws IOException { log.debug("Performing POST request to " + endpointUri + " and expecting JSON response. POST parameters: " + postParams); HttpPost post = new HttpPost(endpointUri); post.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8")); String responseDataString = httpClient.execute(post, new ResponseHandler<String>() { public String handleResponse(HttpResponse response) throws IOException { StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toString(entity); } else { return null; } } throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } }); return jsonMapper.readValue(responseDataString, Map.class); }
From source file:org.devtcg.five.provider.FiveSyncAdapter.java
private static void downloadFileAndUpdateProviderCancelable(final SyncContext context, final AbstractSyncProvider serverDiffs, final HttpGet request, final Uri localUri, final Uri localFeedItemUri, final String columnToUpdate) throws ClientProtocolException, IOException { sClient.execute(request, new ResponseHandler<Void>() { public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException { if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) return null; if (context.hasCanceled()) return null; /*//from w w w. jav a 2 s . c om * Access a temp file path (FiveProvider treats this as a * special case when isTemporary is true and uses a temporary * path to be moved manually during merging). */ ParcelFileDescriptor pfd = serverDiffs.openFile(localUri, "w"); InputStream in = response.getEntity().getContent(); OutputStream out = new ParcelFileDescriptor.AutoCloseOutputStream(pfd); try { IOUtilities.copyStream(in, out); if (context.hasCanceled() == true) return null; /* * Update the record to reflect the newly downloaded uri. * During table merging we'll need to move the file and * update the uri we store here. */ ContentValues values = new ContentValues(); values.put(columnToUpdate, localUri.toString()); serverDiffs.update(localFeedItemUri, values, null, null); } finally { if (in != null) IOUtilities.close(in); if (out != null) IOUtilities.close(out); } return null; } }); }
From source file:org.wikipedia.vlsergey.secretary.jwpf.HttpBot.java
protected void post(final HttpPost postMethod, final ContentProcessable action) throws IOException, ProcessException, CookieException { postMethod.getParams().setParameter("http.protocol.content-charset", MediaWikiBot.ENCODING); postMethod.setHeader("Accept-Encoding", GZIP_CONTENT_ENCODING); httpClient.execute(postMethod, new ResponseHandler<Object>() { @Override/*from ww w . j a v a 2 s . co m*/ public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException { onPostResponse(action, postMethod, response); return null; } }); }
From source file:ss.udapi.sdk.services.HttpServices.java
private ResponseHandler<String> getResponseHandler(final int validStatus) { return new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int responseStatus = response.getStatusLine().getStatusCode(); if (responseStatus == validStatus) { logger.debug("Http connection status " + responseStatus); HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException( "Unexpected http connection response status: " + responseStatus); }/*from w w w .j a v a 2 s . c o m*/ } }; }
From source file:jp.mau.twappremover.MainActivity.java
private boolean login() { HttpPost request = new HttpPost(LOGIN_PAGE); request.addHeader("User-Agent", USER_AGENT); request.addHeader("Referer", TOP_PAGE); request.addHeader("Content-Type", "application/x-www-form-urlencoded"); request.addHeader("Cookie", "_twitter_sess=" + _session_id + "; guest_id=" + _guest_id); List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("session[username_or_email]", _id.getText().toString())); pairs.add(new BasicNameValuePair("session[password]", _pass.getText().toString())); pairs.add(new BasicNameValuePair("remember_me", "1")); pairs.add(new BasicNameValuePair("return_to_ssl", "true")); pairs.add(new BasicNameValuePair("redirect_after_login", " ")); pairs.add(new BasicNameValuePair(KEY_AUTH_TOKEN_TAG, _auth_token)); try {//from w w w . ja v a 2s.c o m request.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8")); String result = _client.execute(request, new ResponseHandler<String>() { @Override public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: return EntityUtils.toString(response.getEntity(), "UTF-8"); case HttpStatus.SC_NOT_FOUND: throw new RuntimeException("not found"); default: throw new RuntimeException("error"); } } }); // ??(signin-wrapper???????) Document doc = Jsoup.parse(result); Elements elm = doc.getElementsByClass("signin-wrapper"); if (elm.size() > 0) return false; // auth_token???? List<Cookie> cookies = _client.getCookieStore().getCookies(); for (Cookie c : cookies) { if (c.getName().equals(KEY_AUTH_TOKEN)) { _cookie_auth = c.getValue(); } } } catch (Exception ex) { ex.printStackTrace(); } return true; }
From source file:net.ymate.platform.module.wechat.support.HttpClientHelper.java
public IMediaFileWrapper doDownload(String url, String content) throws Exception { CloseableHttpClient _httpClient = __doBuildHttpClient(); try {/*w w w . j av a 2s. c o m*/ return _httpClient.execute( RequestBuilder.post().setUri(url) .setEntity(EntityBuilder.create().setContentEncoding(DEFAULT_CHARSET) .setContentType(ContentType.create("application/x-www-form-urlencoded", DEFAULT_CHARSET)) .setText(content).build()) .build(), new ResponseHandler<IMediaFileWrapper>() { public IMediaFileWrapper handleResponse(HttpResponse response) throws IOException { final long _contentLength = response.getEntity().getContentLength(); final String _contentType = response.getEntity().getContentType().getValue(); // final File _tmpFile = File.createTempFile(UUIDUtils.uuid(), null); org.apache.commons.io.FileUtils.copyInputStreamToFile(response.getEntity().getContent(), _tmpFile); // return new IMediaFileWrapper() { public String getErrorMsg() { return null; } public String getFileName() { return null; } public String getSimpleName() { return null; } public String getSuffix() { return null; } public long getContentLength() { return _contentLength; } public String getContentType() { return _contentType; } public InputStream getInputStream() throws IOException { return org.apache.commons.io.FileUtils.openInputStream(_tmpFile); } public void writeTo(File file) throws IOException { if (!_tmpFile.renameTo(file)) { org.apache.commons.io.FileUtils.copyInputStreamToFile(getInputStream(), file); } else { throw new IOException("Cannot write file to disk!"); } } }; } }); } finally { _httpClient.close(); } }