Java Code Examples for org.apache.http.Header

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project airlift, under directory /http-client/src/main/java/io/airlift/http/client/.

Source file: ApacheHttpClient.java

  18 
vote

@Override public String getHeader(String name){
  Header header=response.getFirstHeader(name);
  if (header != null) {
    return header.getValue();
  }
  return null;
}
 

Example 2

From project and-bible, under directory /jsword-tweaks/src/main/java/jsword/org/crosswire/common/util/.

Source file: WebResource.java

  18 
vote

/** 
 * Get the field as a long.
 * @param response The response from the request
 * @param field the header field to check
 * @return the int value for the field
 */
private int getHeaderAsInt(HttpResponse response,String field){
  Header header=response.getFirstHeader(field);
  String value=header.getValue();
  try {
    return Integer.parseInt(value);
  }
 catch (  NumberFormatException ex) {
    return 0;
  }
}
 

Example 3

From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/twitter/extpack/oauth/signpost/commonshttp/.

Source file: HttpRequestAdapter.java

  18 
vote

public String getHeader(String name){
  Header header=request.getFirstHeader(name);
  if (header == null) {
    return null;
  }
  return header.getValue();
}
 

Example 4

From project android_packages_apps_Exchange, under directory /src/com/android/exchange/.

Source file: EasSyncService.java

  18 
vote

/** 
 * Gets the redirect location from the HTTP headers and uses that to modify the HttpPost so that it can be reused
 * @param resp the HttpResponse that indicates a redirect (451)
 * @param post the HttpPost that was originally sent to the server
 * @return the HttpPost, updated with the redirect location
 */
private HttpPost getRedirect(HttpResponse resp,HttpPost post){
  Header locHeader=resp.getFirstHeader("X-MS-Location");
  if (locHeader != null) {
    String loc=locHeader.getValue();
    if (loc != null && loc.startsWith("http")) {
      post.setURI(URI.create(loc));
      return post;
    }
  }
  return null;
}
 

Example 5

From project ardverk-dht, under directory /components/store/src/main/java/org/ardverk/dht/storage/message/.

Source file: Context.java

  18 
vote

public String getStringValue(String name,String defaultValue){
  Header header=getHeader(name);
  if (header != null) {
    return header.getValue();
  }
  return defaultValue;
}
 

Example 6

From project BF3-Battlelog, under directory /src/com/ninetwozero/battlelog/http/.

Source file: RequestHandler.java

  18 
vote

public void process(HttpResponse response,HttpContext context){
  final HttpEntity entity=response.getEntity();
  final Header encoding=entity.getContentEncoding();
  if (encoding != null) {
    for (    HeaderElement element : encoding.getElements()) {
      if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
        response.setEntity(new InflatingEntity(response.getEntity()));
        break;
      }
    }
  }
}
 

Example 7

From project build-info, under directory /build-info-client/src/main/java/org/jfrog/build/util/.

Source file: DependenciesDownloaderHelper.java

  18 
vote

private String validateMd5Checksum(HttpResponse httpResponse,String calculatedMd5) throws IOException {
  Header md5Header=httpResponse.getFirstHeader("X-Checksum-Md5");
  String md5="";
  if (md5Header != null) {
    md5=md5Header.getValue();
    if (!StringUtils.equals(md5,calculatedMd5)) {
      String errorMessage="Calculated MD5 checksum is different from original, " + "Original: '" + md5 + "' Calculated: '"+ calculatedMd5+ "'";
      throw new IOException(errorMessage);
    }
  }
  return md5;
}
 

Example 8

From project components-ness-httpclient, under directory /client/src/main/java/com/nesscomputing/httpclient/factory/httpclient4/.

Source file: InternalResponse.java

  18 
vote

@Override public String getContentType(){
  if (httpResponse != null) {
    final HttpEntity entity=httpResponse.getEntity();
    if (entity != null) {
      final Header contentType=entity.getContentType();
      return (contentType == null) ? null : contentType.getValue();
    }
  }
  return null;
}
 

Example 9

From project crawler4j, under directory /src/main/java/edu/uci/ics/crawler4j/crawler/.

Source file: Page.java

  18 
vote

/** 
 * Loads the content of this page from a fetched HttpEntity.
 */
public void load(HttpEntity entity) throws Exception {
  contentType=null;
  Header type=entity.getContentType();
  if (type != null) {
    contentType=type.getValue();
  }
  contentEncoding=null;
  Header encoding=entity.getContentEncoding();
  if (encoding != null) {
    contentEncoding=encoding.getValue();
  }
  contentCharset=EntityUtils.getContentCharSet(entity);
  contentData=EntityUtils.toByteArray(entity);
}
 

Example 10

From project crest, under directory /core/src/main/java/org/codegist/crest/io/http/.

Source file: HttpClientHttpChannel.java

  18 
vote

public String getContentType(){
  Header header=response.getFirstHeader("Content-Type");
  if (header != null) {
    return header.getValue();
  }
 else {
    return null;
  }
}
 

Example 11

From project droid-fu, under directory /src/main/java/com/github/droidfu/http/.

Source file: BetterHttp.java

  18 
vote

public void process(final HttpResponse response,final HttpContext context){
  final HttpEntity entity=response.getEntity();
  final Header encoding=entity.getContentEncoding();
  if (encoding != null) {
    for (    HeaderElement element : encoding.getElements()) {
      if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
        response.setEntity(new GZIPInflatingEntity(response.getEntity()));
        break;
      }
    }
  }
}
 

Example 12

From project fanfoudroid, under directory /src/com/ch_linghu/fanfoudroid/http/.

Source file: HttpClient.java

  18 
vote

@Override public void process(HttpResponse response,HttpContext context) throws org.apache.http.HttpException, IOException {
  HttpEntity entity=response.getEntity();
  Header ceheader=entity.getContentEncoding();
  if (ceheader != null) {
    HeaderElement[] codecs=ceheader.getElements();
    for (int i=0; i < codecs.length; i++) {
      if (codecs[i].getName().equalsIgnoreCase("gzip")) {
        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
        return;
      }
    }
  }
}
 

Example 13

From project gnip4j, under directory /http/src/main/java/com/zaubersoftware/gnip4j/http/.

Source file: GZipInterceptor.java

  18 
vote

/** 
 * @see HttpResponseInterceptor#process(HttpResponse,HttpContext) 
 */
public final void process(final HttpResponse response,final HttpContext context) throws HttpException, IOException {
  final HttpEntity entity=response.getEntity();
  final Header ceheader=entity.getContentEncoding();
  if (ceheader != null) {
    final HeaderElement[] codecs=ceheader.getElements();
    for (int i=0; i < codecs.length; i++) {
      if (codecs[i].getName().equalsIgnoreCase("gzip")) {
        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
        return;
      }
    }
  }
}
 

Example 14

From project httpbuilder, under directory /src/main/java/groovyx/net/http/.

Source file: ContentEncoding.java

  18 
vote

protected boolean hasEncoding(final HttpResponse response,final String encoding){
  HttpEntity entity=response.getEntity();
  if (entity == null)   return false;
  Header ceHeader=entity.getContentEncoding();
  if (ceHeader == null)   return false;
  HeaderElement[] codecs=ceHeader.getElements();
  for (int i=0; i < codecs.length; i++)   if (encoding.equalsIgnoreCase(codecs[i].getName()))   return true;
  return false;
}
 

Example 15

From project httpClient, under directory /httpclient/src/main/java/org/apache/http/client/methods/.

Source file: RequestBuilder.java

  18 
vote

public RequestBuilder removeHeaders(final String name){
  if (name == null || headergroup == null) {
    return this;
  }
  for (HeaderIterator i=headergroup.iterator(); i.hasNext(); ) {
    Header header=i.nextHeader();
    if (name.equalsIgnoreCase(header.getName())) {
      i.remove();
    }
  }
  return this;
}
 

Example 16

From project accesointeligente, under directory /src/org/accesointeligente/server/robots/.

Source file: SIAC.java

  17 
vote

public void detectCharacterEncoding(){
  HttpGet get;
  HttpResponse response;
  Header contentType;
  Pattern pattern;
  Matcher matcher;
  try {
    get=new HttpGet(baseUrl + "/formulario.gov?accion=ingresa");
    response=client.execute(get);
    contentType=response.getFirstHeader("Content-Type");
    EntityUtils.consume(response.getEntity());
    if (contentType == null || contentType.getValue() == null) {
      characterEncoding="ISO-8859-1";
    }
    pattern=Pattern.compile(".*charset=(.+)");
    matcher=pattern.matcher(contentType.getValue());
    if (!matcher.matches()) {
      characterEncoding="ISO-8859-1";
    }
    characterEncoding=matcher.group(1);
  }
 catch (  Exception e) {
    characterEncoding="ISO-8859-1";
  }
}
 

Example 17

From project amber, under directory /oauth-2.0/httpclient4/src/main/java/org/apache/amber/oauth2/httpclient4/.

Source file: HttpClient4.java

  17 
vote

public <T extends OAuthClientResponse>T execute(OAuthClientRequest request,Map<String,String> headers,String requestMethod,Class<T> responseClass) throws OAuthSystemException, OAuthProblemException {
  try {
    URI location=new URI(request.getLocationUri());
    HttpRequestBase req=null;
    String responseBody="";
    if (!OAuthUtils.isEmpty(requestMethod) && OAuth.HttpMethod.POST.equals(requestMethod)) {
      req=new HttpPost(location);
      HttpEntity entity=new StringEntity(request.getBody());
      ((HttpPost)req).setEntity(entity);
    }
 else {
      req=new HttpGet(location);
    }
    if (headers != null && !headers.isEmpty()) {
      for (      Map.Entry<String,String> header : headers.entrySet()) {
        req.setHeader(header.getKey(),header.getValue());
      }
    }
    HttpResponse response=client.execute(req);
    Header contentTypeHeader=null;
    HttpEntity entity=response.getEntity();
    if (entity != null) {
      responseBody=EntityUtils.toString(entity);
      contentTypeHeader=entity.getContentType();
    }
    String contentType=null;
    if (contentTypeHeader != null) {
      contentType=contentTypeHeader.toString();
    }
    return OAuthClientResponseFactory.createCustomResponse(responseBody,contentType,response.getStatusLine().getStatusCode(),responseClass);
  }
 catch (  Exception e) {
    throw new OAuthSystemException(e);
  }
}
 

Example 18

From project android-async-http, under directory /src/com/loopj/android/http/.

Source file: BinaryHttpResponseHandler.java

  17 
vote

void sendResponseMessage(HttpResponse response){
  StatusLine status=response.getStatusLine();
  Header[] contentTypeHeaders=response.getHeaders("Content-Type");
  byte[] responseBody=null;
  if (contentTypeHeaders.length != 1) {
    sendFailureMessage(new HttpResponseException(status.getStatusCode(),"None, or more than one, Content-Type Header found!"),responseBody);
    return;
  }
  Header contentTypeHeader=contentTypeHeaders[0];
  boolean foundAllowedContentType=false;
  for (  String anAllowedContentType : mAllowedContentTypes) {
    if (anAllowedContentType.equals(contentTypeHeader.getValue())) {
      foundAllowedContentType=true;
    }
  }
  if (!foundAllowedContentType) {
    sendFailureMessage(new HttpResponseException(status.getStatusCode(),"Content-Type not allowed!"),responseBody);
    return;
  }
  try {
    HttpEntity entity=null;
    HttpEntity temp=response.getEntity();
    if (temp != null) {
      entity=new BufferedHttpEntity(temp);
    }
    responseBody=EntityUtils.toByteArray(entity);
  }
 catch (  IOException e) {
    sendFailureMessage(e,(byte[])null);
  }
  if (status.getStatusCode() >= 300) {
    sendFailureMessage(new HttpResponseException(status.getStatusCode(),status.getReasonPhrase()),responseBody);
  }
 else {
    sendSuccessMessage(responseBody);
  }
}
 

Example 19

From project android-rackspacecloud, under directory /src/com/rackspace/cloud/servers/api/client/http/.

Source file: HttpBundle.java

  17 
vote

private String getCurl(HttpEntityEnclosingRequestBase message){
  StringBuilder result=new StringBuilder("curl -verbose -X ");
  result.append(message.getMethod());
  HeaderIterator itr=message.headerIterator();
  while (itr.hasNext()) {
    Header header=itr.nextHeader();
    String key=header.getName();
    String value=header.getValue();
    if (key.equals("X-Auth-Token") || key.equals("X-Auth-Key")) {
      value="<secret>";
    }
    result.append(" -H \"" + key + ": "+ value+ "\"");
  }
  HttpEntity entity=message.getEntity();
  String xmlBody=null;
  if (entity != null) {
    try {
      xmlBody=EntityUtils.toString(entity);
    }
 catch (    ParseException e) {
      e.printStackTrace();
    }
catch (    IOException e) {
      e.printStackTrace();
    }
  }
  if (xmlBody != null && !xmlBody.equals("")) {
    result.append(" -d \"<?xml version=\"1.0\" encoding=\"UTF-8\"?> " + xmlBody + "\"");
  }
  result.append(" " + message.getURI());
  return result.toString();
}
 

Example 20

From project AndroidDevWeekendDub-BookLibrary, under directory /src/org/curiouscreature/android/shelves/provider/.

Source file: BooksUpdater.java

  17 
vote

private boolean bookCoverUpdated(BooksStore.Book book,ImageUtilities.ExpiringBitmap expiring){
  expiring.lastModified=null;
  final HttpGet get=new HttpGet(book.getImageUrl(BooksStore.ImageSize.TINY));
  HttpEntity entity=null;
  try {
    final HttpResponse response=HttpManager.execute(get);
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
      entity=response.getEntity();
      final Header header=response.getFirstHeader("Last-Modified");
      if (header != null) {
        final Calendar calendar=GregorianCalendar.getInstance();
        try {
          calendar.setTime(mLastModifiedFormat.parse(header.getValue()));
          expiring.lastModified=calendar;
          return calendar.after(book.getLastModified());
        }
 catch (        ParseException e) {
          return false;
        }
      }
    }
  }
 catch (  IOException e) {
    android.util.Log.e(LOG_TAG,"Could not check modification date for " + book,e);
  }
 finally {
    if (entity != null) {
      try {
        entity.consumeContent();
      }
 catch (      IOException e) {
        android.util.Log.e(LOG_TAG,"Could not check modification date for " + book,e);
      }
    }
  }
  return false;
}
 

Example 21

From project androidquery, under directory /tests/src/com/androidquery/test/.

Source file: AQueryAsyncTest.java

  17 
vote

public void testAjaxHeadersGet(){
  String url="http://www.google.com";
  aq.ajax(url,String.class,new AjaxCallback<String>(){
    @Override public void callback(    String url,    String json,    AjaxStatus status){
      done(url,json,status);
    }
  }
);
  waitAsync();
  assertNotNull(result);
  List<Header> headers=status.getHeaders();
  assertTrue(headers.size() > 0);
  Header c=headers.get(0);
  AQUtility.debug(c.getName(),c.getValue());
}
 

Example 22

From project android_7, under directory /src/org/immopoly/android/helper/.

Source file: WebHelper.java

  17 
vote

public static JSONArray postFlatIdsHttpData(String url,JSONObject jsonObject) throws JSONException {
  try {
    InputStream in;
    HttpResponse response=postHttp(url,jsonObject);
    Header contentEncoding=response.getFirstHeader("Content-Encoding");
    if (response != null && contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
      in=new GZIPInputStream(response.getEntity().getContent());
    }
 else {
      in=new BufferedInputStream(response.getEntity().getContent());
    }
    String s=readInputStream(in);
    return new JSONArray(s);
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 23

From project Anki-Android, under directory /src/com/tomgibara/android/veecheck/.

Source file: VeecheckThread.java

  17 
vote

private VeecheckResult performRequest(VeecheckVersion version,String uri) throws ClientProtocolException, IOException, IllegalStateException, SAXException {
  HttpClient client=new DefaultHttpClient();
  HttpParams params=client.getParams();
  HttpConnectionParams.setConnectionTimeout(params,CONNECTION_TIMEOUT);
  HttpConnectionParams.setSoTimeout(params,SO_TIMEOUT);
  HttpGet request=new HttpGet(version.substitute(uri));
  HttpResponse response=client.execute(request);
  HttpEntity entity=response.getEntity();
  try {
    StatusLine line=response.getStatusLine();
    if (line.getStatusCode() != 200) {
      throw new IOException("Request failed: " + line.getReasonPhrase());
    }
    Header header=response.getFirstHeader(HTTP.CONTENT_TYPE);
    Encoding encoding=identityEncoding(header);
    VeecheckResult handler=new VeecheckResult(version);
    Xml.parse(entity.getContent(),encoding,handler);
    return handler;
  }
  finally {
    entity.consumeContent();
  }
}
 

Example 24

From project apps-for-android, under directory /Samples/Downloader/src/com/google/android/downloader/.

Source file: DownloaderActivity.java

  17 
vote

private long getSize(String url) throws ClientProtocolException, IOException {
  url=normalizeUrl(url);
  Log.i(LOG_TAG,"Head " + url);
  HttpHead httpGet=new HttpHead(url);
  HttpResponse response=mHttpClient.execute(httpGet);
  if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
    throw new IOException("Unexpected Http status code " + response.getStatusLine().getStatusCode());
  }
  Header[] clHeaders=response.getHeaders("Content-Length");
  if (clHeaders.length > 0) {
    Header header=clHeaders[0];
    return Long.parseLong(header.getValue());
  }
  return -1;
}
 

Example 25

From project AquaNotesTest, under directory /src/com/google/android/apps/iosched/service/.

Source file: SyncService.java

  17 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSoTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.addResponseInterceptor(new HttpResponseInterceptor(){
    public void process(    HttpResponse response,    HttpContext context){
      final HttpEntity entity=response.getEntity();
      final Header encoding=entity.getContentEncoding();
      if (encoding != null) {
        for (        HeaderElement element : encoding.getElements()) {
          if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
            response.setEntity(new InflatingEntity(response.getEntity()));
            break;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 26

From project be.norio.twunch.android, under directory /src/be/norio/twunch/android/service/.

Source file: SyncService.java

  17 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSoTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.addResponseInterceptor(new HttpResponseInterceptor(){
    public void process(    HttpResponse response,    HttpContext context){
      final HttpEntity entity=response.getEntity();
      final Header encoding=entity.getContentEncoding();
      if (encoding != null) {
        for (        HeaderElement element : encoding.getElements()) {
          if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
            response.setEntity(new InflatingEntity(response.getEntity()));
            break;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 27

From project c2dm4j, under directory /src/main/java/org/whispercomm/c2dm4j/impl/.

Source file: C2dmHttpResponseHandler.java

  17 
vote

private Date getRetryAfter(HttpResponse response){
  Header retryAfterHeader=response.getFirstHeader("Retry-After");
  if (retryAfterHeader != null) {
    try {
      return org.apache.http.impl.cookie.DateUtils.parseDate(retryAfterHeader.getValue());
    }
 catch (    DateParseException e) {
    }
    try {
      return new Date(System.currentTimeMillis() + 1000L * Integer.valueOf(retryAfterHeader.getValue()));
    }
 catch (    NumberFormatException e) {
    }
  }
  return null;
}
 

Example 28

From project capedwarf-green, under directory /connect/src/main/java/org/jboss/capedwarf/connect/server/.

Source file: ServerProxyHandler.java

  17 
vote

/** 
 * Get content as a input stream.
 * @param qi     the additional client query info
 * @param entity the http entity
 * @return the response input stream
 * @throws Throwable for any error
 */
protected Result getResultWithHttpEntity(QueryInfo qi,HttpEntity entity) throws Throwable {
  String link=config.getEndpoint(qi.secure) + qi.query;
  if (config.isDebugLogging())   getEnv().log(Constants.TAG_CONNECTION,Level.INFO,"URL: " + link,null);
  HttpPost httppost=new HttpPost(link);
  if (entity != null)   httppost.setEntity(entity);
  for (  Header header : HttpHeaders.getHeaders()) {
    httppost.addHeader(header);
  }
  if (qi.secure) {
    Environment env=EnvironmentFactory.getEnvironment();
    long id=env.getUserId();
    String token=env.getUserToken();
    httppost.addHeader(Constants.CLIENT_ID,String.valueOf(id));
    httppost.addHeader(Constants.CLIENT_TOKEN,token);
  }
  if (GzipOptionalSerializator.isGzipEnabled()) {
    httppost.addHeader(Constants.CONTENT_ENCODING,Constants.GZIP);
  }
  Result result=new Result();
  try {
    HttpResponse response=getClient().execute(httppost);
    result.status=response.getStatusLine().getStatusCode();
    Header h=response.getFirstHeader("Content-Length");
    if (h != null)     result.contentLength=Long.parseLong(h.getValue());
    result.stream=response.getEntity().getContent();
  }
  finally {
    result.end();
  }
  return result;
}
 

Example 29

From project conference-mobile-app, under directory /android-app/src/com/google/android/apps/iosched/service/.

Source file: SyncService.java

  17 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSoTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.addResponseInterceptor(new HttpResponseInterceptor(){
    public void process(    HttpResponse response,    HttpContext context){
      final HttpEntity entity=response.getEntity();
      final Header encoding=entity.getContentEncoding();
      if (encoding != null) {
        for (        HeaderElement element : encoding.getElements()) {
          if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
            response.setEntity(new InflatingEntity(response.getEntity()));
            break;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 30

From project daap, under directory /src/main/java/org/ardverk/daap/.

Source file: DaapRequestProcessor.java

  17 
vote

private long[] getRange(DaapRequest request) throws IOException {
  Header rangeHeader=request.getHeader("Range");
  if (rangeHeader != null) {
    try {
      StringTokenizer tok=new StringTokenizer(rangeHeader.getValue(),"=");
      String key=tok.nextToken().trim();
      if (key.equals("bytes") == false) {
        if (LOG.isInfoEnabled())         LOG.info("Unknown range type: " + key);
        return null;
      }
      byte[] range=tok.nextToken().getBytes(DaapUtil.ISO_8859_1);
      int q=0;
      for (; q < range.length && range[q] != '-'; q++)       ;
      long pos=-1;
      long end=-1;
      pos=Long.parseLong(new String(range,0,q));
      q++;
      if (range.length - q != 0) {
        end=Long.parseLong(new String(range,q,range.length - q));
      }
      return (new long[]{pos,end});
    }
 catch (    NoSuchElementException err) {
      LOG.error("NoSuchElementException",err);
    }
catch (    NumberFormatException err) {
      LOG.error("NumberFormatException",err);
    }
  }
  return (new long[]{0,-1});
}
 

Example 31

From project dccsched, under directory /src/com/underhilllabs/dccsched/service/.

Source file: SyncService.java

  17 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSoTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.addResponseInterceptor(new HttpResponseInterceptor(){
    public void process(    HttpResponse response,    HttpContext context){
      final HttpEntity entity=response.getEntity();
      final Header encoding=entity.getContentEncoding();
      if (encoding != null) {
        for (        HeaderElement element : encoding.getElements()) {
          if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
            response.setEntity(new InflatingEntity(response.getEntity()));
            break;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 32

From project dcnyc10-android, under directory /android/src/com/lullabot/android/apps/iosched/service/.

Source file: SyncService.java

  17 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSoTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.addResponseInterceptor(new HttpResponseInterceptor(){
    public void process(    HttpResponse response,    HttpContext context){
      final HttpEntity entity=response.getEntity();
      final Header encoding=entity.getContentEncoding();
      if (encoding != null) {
        for (        HeaderElement element : encoding.getElements()) {
          if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
            response.setEntity(new InflatingEntity(response.getEntity()));
            break;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 33

From project devoxx-france-android-in-fine, under directory /src/com/infine/android/devoxx/service/.

Source file: RestService.java

  17 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * 1000);
  HttpConnectionParams.setSoTimeout(params,20 * 1000);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.addResponseInterceptor(new HttpResponseInterceptor(){
    public void process(    HttpResponse response,    HttpContext context){
      final HttpEntity entity=response.getEntity();
      final Header encoding=entity.getContentEncoding();
      if (encoding != null) {
        for (        HeaderElement element : encoding.getElements()) {
          if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
            response.setEntity(new InflatingEntity(response.getEntity()));
            break;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 34

From project DirectMemory, under directory /server/directmemory-server-client/src/main/java/org/apache/directmemory/server/client/providers/httpclient/.

Source file: HttpClientDirectMemoryHttpClient.java

  17 
vote

@Override public DirectMemoryResponse put(DirectMemoryRequest request) throws DirectMemoryException {
  String uri=buildRequestWithKey(request);
  log.debug("put request to: {}",uri);
  HttpPut httpPut=new HttpPut(uri);
  httpPut.addHeader("Content-Type",getRequestContentType(request));
  if (request.getExpiresIn() > 0) {
    httpPut.addHeader(DirectMemoryHttpConstants.EXPIRES_IN_HTTP_HEADER,Integer.toString(request.getExpiresIn()));
  }
  if (request.getExchangeType() == ExchangeType.TEXT_PLAIN) {
    httpPut.addHeader(DirectMemoryHttpConstants.SERIALIZER_HTTP_HEADER,request.getSerializer().getClass().getName());
  }
  httpPut.setEntity(new ByteArrayEntity(getPutContent(request)));
  try {
    HttpResponse response=httpClient.execute(httpPut);
    StatusLine statusLine=response.getStatusLine();
switch (statusLine.getStatusCode()) {
case 200:
      Header header=response.getFirstHeader(DirectMemoryHttpConstants.EXPIRES_SERIALIZE_SIZE);
    int storedSize=header == null ? -1 : Integer.valueOf(header.getValue());
  return new DirectMemoryResponse().setStored(Boolean.TRUE).setStoredSize(storedSize);
case 204:
return new DirectMemoryResponse().setStored(Boolean.FALSE);
default :
throw new DirectMemoryException("put cache content return http code:'" + statusLine.getStatusCode() + "', reasonPhrase:"+ statusLine.getReasonPhrase());
}
}
 catch (IOException e) {
throw new DirectMemoryException(e.getMessage(),e);
}
}
 

Example 35

From project DiscogsForAndroid, under directory /src/com/discogs/services/.

Source file: NetworkHelper.java

  17 
vote

private void initHTTPClient(){
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  HttpParams params=new BasicHttpParams();
  HttpProtocolParams.setContentCharset(params,"utf-8");
  params.setBooleanParameter("http.protocol.expect-continue",false);
  HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setContentCharset(params,HTTP.DEFAULT_CONTENT_CHARSET);
  HttpProtocolParams.setUseExpectContinue(params,true);
  ThreadSafeClientConnManager connectionManager=new ThreadSafeClientConnManager(params,schemeRegistry);
  httpClient=new DefaultHttpClient(connectionManager,params);
  httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3,false));
  httpClient.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    final HttpRequest request,    final HttpContext context) throws HttpException, IOException {
      if (!request.containsHeader("Accept-Encoding")) {
        request.addHeader("Accept-Encoding","gzip");
      }
    }
  }
);
  httpClient.addResponseInterceptor(new HttpResponseInterceptor(){
    public void process(    final HttpResponse response,    final HttpContext context) throws HttpException, IOException {
      HttpEntity entity=response.getEntity();
      if (entity != null) {
        Header ceheader=entity.getContentEncoding();
        if (ceheader != null) {
          HeaderElement[] codecs=ceheader.getElements();
          for (int i=0; i < codecs.length; i++) {
            if (codecs[i].getName().equalsIgnoreCase("gzip")) {
              response.setEntity(new GzipDecompressingEntity(response.getEntity()));
              return;
            }
          }
        }
      }
    }
  }
);
}
 

Example 36

From project DownloadProvider, under directory /src/com/mozillaonline/providers/downloads/.

Source file: DownloadThread.java

  17 
vote

/** 
 * Handle a 3xx redirect status.
 */
private void handleRedirect(State state,HttpResponse response,int statusCode) throws StopRequest, RetryDownload {
  if (Constants.LOGVV) {
    Log.v(Constants.TAG,"got HTTP redirect " + statusCode);
  }
  if (state.mRedirectCount >= Constants.MAX_REDIRECTS) {
    throw new StopRequest(Downloads.STATUS_TOO_MANY_REDIRECTS,"too many redirects");
  }
  Header header=response.getFirstHeader("Location");
  if (header == null) {
    return;
  }
  if (Constants.LOGVV) {
    Log.v(Constants.TAG,"Location :" + header.getValue());
  }
  String newUri;
  try {
    newUri=new URI(mInfo.mUri).resolve(new URI(header.getValue())).toString();
  }
 catch (  URISyntaxException ex) {
    if (Constants.LOGV) {
      Log.d(Constants.TAG,"Couldn't resolve redirect URI " + header.getValue() + " for "+ mInfo.mUri);
    }
    throw new StopRequest(Downloads.STATUS_HTTP_DATA_ERROR,"Couldn't resolve redirect URI");
  }
  ++state.mRedirectCount;
  state.mRequestUri=newUri;
  if (statusCode == 301 || statusCode == 303) {
    state.mNewUri=newUri;
  }
  throw new RetryDownload();
}
 

Example 37

From project droidparts, under directory /extra/src/org/droidparts/http/.

Source file: RESTClient.java

  17 
vote

public String put(String uri,String contentEncoding,String data) throws HTTPException {
  L.d("PUT on " + uri + ", data: "+ data);
  HttpPut req=new HttpPut(uri);
  try {
    StringEntity entity=new StringEntity(data,UTF8);
    entity.setContentType(contentEncoding);
    req.setEntity(entity);
  }
 catch (  UnsupportedEncodingException e) {
    throw new HTTPException(e);
  }
  DefaultHttpClientWrapper wrapper=getLegacy();
  HttpResponse resp=wrapper.getResponse(req);
  Header loc=resp.getLastHeader("Location");
  DefaultHttpClientWrapper.consumeResponse(resp);
  if (loc != null) {
    String[] parts=loc.getValue().split("/");
    String location=parts[parts.length - 1];
    L.d("location: " + location);
    return location;
  }
 else {
    return null;
  }
}
 

Example 38

From project EasySOA, under directory /easysoa-proxy/easysoa-proxy-core/easysoa-proxy-core-httpdiscoveryproxy/src/main/java/org/easysoa/proxy/.

Source file: HttpResponseHandler.java

  17 
vote

public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
  Header contentEncodingHeader=response.getFirstHeader("Content-Encoding");
  StringBuffer responseBuffer=new StringBuffer();
  if (contentEncodingHeader != null) {
    byte[] buf=new byte[512];
    int len;
    ByteArrayOutputStream bos=new ByteArrayOutputStream();
    if ("gzip".equalsIgnoreCase(contentEncodingHeader.getValue())) {
      GZIPInputStream gzipInputStream=new GZIPInputStream(response.getEntity().getContent());
      while ((len=gzipInputStream.read(buf,0,512)) != -1) {
        bos.write(buf,0,len);
      }
      responseBuffer.append(new String(bos.toByteArray()));
    }
 else     if ("zip".equalsIgnoreCase(contentEncodingHeader.getValue())) {
      ZipInputStream zipInputStream=new ZipInputStream(response.getEntity().getContent());
      while ((len=zipInputStream.read(buf,0,512)) != -1) {
        bos.write(buf,0,len);
      }
      responseBuffer.append(new String(bos.toByteArray()));
    }
 else {
      logger.error("Unable to deflate this Content-Encoding : " + contentEncodingHeader.getValue());
      throw new IOException("Unable to deflate this Content-Encoding : " + contentEncodingHeader.getValue());
    }
  }
 else {
    InputStreamReader in=new InputStreamReader(response.getEntity().getContent());
    BufferedReader bin=new BufferedReader(in);
    String line;
    do {
      line=bin.readLine();
      if (line != null) {
        responseBuffer.append(line);
      }
    }
 while (line != null);
  }
  return responseBuffer.toString();
}
 

Example 39

From project eoit, under directory /EOIT/src/fr/eoit/util/.

Source file: AndroidUrlDownloader.java

  17 
vote

@Override public InputStream urlToInputStream(String url) throws DownloadException {
  try {
    HttpClient httpclient=new DefaultHttpClient();
    HttpGet httpget=new HttpGet(url);
    httpget.addHeader("Accept-Encoding","gzip");
    HttpResponse response;
    response=httpclient.execute(httpget);
    Log.v(LOG_TAG,response.getStatusLine().toString());
    HttpEntity entity=response.getEntity();
    if (entity != null) {
      InputStream instream=entity.getContent();
      Header contentEncoding=response.getFirstHeader("Content-Encoding");
      if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
        Log.v(LOG_TAG,"Accepting gzip for url : " + url);
        instream=new GZIPInputStream(instream);
      }
      return instream;
    }
  }
 catch (  IllegalStateException e) {
    throw new DownloadException(e);
  }
catch (  IOException e) {
    throw new DownloadException(e);
  }
  return null;
}
 

Example 40

From project exo.social.client, under directory /src/main/java/org/exoplatform/social/client/api/util/.

Source file: SocialHttpClientSupport.java

  17 
vote

/** 
 * Invokes the social rest service via Get method
 * @param targetURL 
 * @param authPolicy POLICY.NO_AUTH/POLICY.BASIC_AUTH
 * @param params HttpParams for Request
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 */
public static HttpResponse executeGet(String targetURL,POLICY authPolicy,HttpParams params) throws SocialHttpClientException {
  SocialHttpClient httpClient=SocialHttpClientImpl.newInstance();
  if (POLICY.BASIC_AUTH == authPolicy) {
    try {
      httpClient.setBasicAuthenticateToRequest();
    }
 catch (    SocialClientLibException e) {
      throw new SocialHttpClientException(e.getMessage(),e);
    }
  }
  HttpGet httpGet=new HttpGet(targetURL);
  Header header=new BasicHeader("Content-Type","application/json");
  httpGet.setHeader(header);
  HttpHost targetHost=new HttpHost(SocialClientContext.getHost(),SocialClientContext.getPort(),SocialClientContext.getProtocol());
  if (params != null) {
    httpGet.setParams(params);
  }
  try {
    HttpResponse response=httpClient.execute(targetHost,httpGet);
    if (SocialClientContext.isDeveloping()) {
      dumpHttpResponsetHeader(response);
      dumpContent(response);
    }
    return response;
  }
 catch (  ClientProtocolException cpex) {
    throw new SocialHttpClientException(cpex.toString(),cpex);
  }
catch (  IOException ioex) {
    throw new SocialHttpClientException(ioex.toString(),ioex);
  }
}
 

Example 41

From project gddsched2, under directory /trunk/android/src/com/google/android/apps/iosched2/service/.

Source file: SyncService.java

  17 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSoTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.addResponseInterceptor(new HttpResponseInterceptor(){
    public void process(    HttpResponse response,    HttpContext context){
      final HttpEntity entity=response.getEntity();
      final Header encoding=entity.getContentEncoding();
      if (encoding != null) {
        for (        HeaderElement element : encoding.getElements()) {
          if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
            response.setEntity(new InflatingEntity(response.getEntity()));
            break;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 42

From project android-api_1, under directory /android-lib/src/com/android/http/multipart/.

Source file: MultipartEntity.java

  15 
vote

@Override public Header getContentType(){
  StringBuffer buffer=new StringBuffer(MULTIPART_FORM_CONTENT_TYPE);
  buffer.append("; boundary=");
  buffer.append(EncodingUtils.getAsciiString(getMultipartBoundary()));
  return new BasicHeader(HTTP.CONTENT_TYPE,buffer.toString());
}
 

Example 43

From project android-shuffle, under directory /client/src/org/dodgybits/shuffle/android/synchronisation/tracks/.

Source file: WebClient.java

  15 
vote

protected synchronized String postContentToUrl(String url,String content) throws ApiException {
  if (sUserAgent == null) {
    throw new ApiException("User-Agent string must be prepared");
  }
  HttpClient client=CreateClient();
  java.net.URI uri=URI.create(url);
  HttpHost host=GetHost(uri);
  HttpPost request=new HttpPost(uri.getPath());
  request.setHeader("User-Agent",sUserAgent);
  request.setHeader("Content-Type","text/xml");
  HttpEntity ent;
  try {
    ent=new StringEntity(content,"UTF-8");
  }
 catch (  UnsupportedEncodingException e) {
    throw new ApiException("unsupported encoding set",e);
  }
  request.setEntity(ent);
  try {
    HttpResponse response=client.execute(host,request);
    StatusLine status=response.getStatusLine();
    Log.i(cTag,"post with response " + status.toString());
    if (status.getStatusCode() != HttpStatus.SC_CREATED) {
      throw new ApiException("Invalid response from server: " + status.toString() + " for content: "+ content);
    }
    Header[] header=response.getHeaders("Location");
    if (header.length != 0)     return header[0].getValue();
 else     return null;
  }
 catch (  IOException e) {
    throw new ApiException("Problem communicating with API",e);
  }
}
 

Example 44

From project android_external_oauth, under directory /core/src/main/java/net/oauth/client/httpclient4/.

Source file: HttpMethodResponse.java

  15 
vote

private List<Map.Entry<String,String>> getHeaders(){
  List<Map.Entry<String,String>> headers=new ArrayList<Map.Entry<String,String>>();
  Header[] allHeaders=httpResponse.getAllHeaders();
  if (allHeaders != null) {
    for (    Header header : allHeaders) {
      headers.add(new OAuth.Parameter(header.getName(),header.getValue()));
    }
  }
  return headers;
}
 

Example 45

From project capedwarf-blue, under directory /urlfetch/src/main/java/org/jboss/capedwarf/urlfetch/.

Source file: HTTPResponseHack.java

  15 
vote

HTTPResponseHack(HttpResponse response) throws Exception {
  createResponse(response.getStatusLine().getStatusCode());
  for (  Header h : response.getAllHeaders())   addHeader(h.getName(),h.getValue());
  InputStream is=response.getEntity().getContent();
  setContent(IOUtils.toBytes(is,true));
}
 

Example 46

From project CHMI, under directory /src/org/kaldax/lib/net/http/.

Source file: Downloader.java

  15 
vote

public String getETag(String fileURL) throws IOException, InterruptedException {
  DefaultHttpClient httpclient=new DefaultHttpClient();
  httpclient.getParams().setLongParameter("http.connection-manager.timeout",new Long(iTimeout * 1000));
  httpclient.getParams().setIntParameter("http.connection.timeout",iTimeout * 1000);
  httpclient.getParams().setIntParameter("http.socket.timeout",iTimeout * 1000);
  HttpGet httpget=new HttpGet(fileURL);
  HttpResponse response=httpclient.execute(httpget);
  HttpEntity entity=response.getEntity();
  if (response.getStatusLine().getStatusCode() != 200) {
    throw new IOException("HTTP error, code=" + new Integer(response.getStatusLine().getStatusCode()).toString());
  }
  Header[] headers=response.getAllHeaders();
  for (  Header hdr : headers) {
    if (hdr.getName().compareToIgnoreCase("Etag") == 0) {
      return hdr.getValue();
    }
  }
  return null;
}
 

Example 47

From project couchdb4j, under directory /src/java/com/fourspaces/couchdb/.

Source file: CouchResponse.java

  15 
vote

/** 
 * Retrieves a specific header from the response (not really used anymore)
 * @param key
 * @return
 */
public String getHeader(String key){
  for (  Header h : headers) {
    if (h.getName().equals(key)) {
      return h.getValue();
    }
  }
  return null;
}
 

Example 48

From project DeskSMS, under directory /DeskSMS/src/com/koushikdutta/desktopsms/.

Source file: TickleServiceHelper.java

  15 
vote

static String getCookie(final Context context) throws ClientProtocolException, IOException, URISyntaxException {
  Settings settings=Settings.getInstance(context);
  final String authToken=settings.getString("web_connect_auth_token");
  if (authToken == null)   return null;
  Log.i(LOGTAG,authToken);
  Log.i(LOGTAG,"getting cookie");
  DefaultHttpClient client=new DefaultHttpClient();
  String continueURL=ServiceHelper.BASE_URL;
  URI uri=new URI(ServiceHelper.AUTH_URL + "?continue=" + URLEncoder.encode(continueURL,"UTF-8")+ "&auth="+ authToken);
  HttpGet method=new HttpGet(uri);
  final HttpParams getParams=new BasicHttpParams();
  HttpClientParams.setRedirecting(getParams,false);
  method.setParams(getParams);
  HttpResponse res=client.execute(method);
  Header[] headers=res.getHeaders("Set-Cookie");
  if (res.getStatusLine().getStatusCode() != 302 || headers.length == 0) {
    return null;
  }
  String ascidCookie=null;
  for (  Header header : headers) {
    if (header.getValue().indexOf("ACSID=") >= 0) {
      String value=header.getValue();
      String[] pairs=value.split(";");
      ascidCookie=pairs[0];
    }
  }
  settings.setString("Cookie",ascidCookie);
  return ascidCookie;
}
 

Example 49

From project eucalyptus, under directory /clc/modules/axis2-transport/src/edu/ucsb/eucalyptus/transport/http/.

Source file: Axis2HttpWorker.java

  15 
vote

private Handler.InvocationResponse handleGet(final AxisHttpRequest request,final AxisHttpResponse response,final MessageContext msgContext) throws AxisFault {
  Handler.InvocationResponse pi;
  String contentType=null;
  Header[] headers=request.getHeaders(HTTPConstants.HEADER_CONTENT_TYPE);
  if (headers != null && headers.length > 0) {
    contentType=headers[0].getValue();
    int index=contentType.indexOf(';');
    if (index > 0) {
      contentType=contentType.substring(0,index);
    }
  }
  pi=Axis2HttpWorker.processURLRequest(msgContext,response.getOutputStream(),contentType);
  return pi;
}
 

Example 50

From project Fotolia-API, under directory /java/libs/httpcomponents-client-4.1.2/examples/org/apache/http/examples/client/.

Source file: ClientExecuteDirect.java

  15 
vote

public static void main(String[] args) throws Exception {
  DefaultHttpClient httpclient=new DefaultHttpClient();
  try {
    HttpHost target=new HttpHost("www.apache.org",80,"http");
    HttpGet req=new HttpGet("/");
    System.out.println("executing request to " + target);
    HttpResponse rsp=httpclient.execute(target,req);
    HttpEntity entity=rsp.getEntity();
    System.out.println("----------------------------------------");
    System.out.println(rsp.getStatusLine());
    Header[] headers=rsp.getAllHeaders();
    for (int i=0; i < headers.length; i++) {
      System.out.println(headers[i]);
    }
    System.out.println("----------------------------------------");
    if (entity != null) {
      System.out.println(EntityUtils.toString(entity));
    }
  }
  finally {
    httpclient.getConnectionManager().shutdown();
  }
}
 

Example 51

From project GraduationProject, under directory /G-Card/src/Hello/Tab/Widget/.

Source file: AppEngineClient.java

  15 
vote

private HttpResponse makeRequestNoRetry(String urlPath,List<NameValuePair> params,boolean newToken) throws Exception {
  Account account=new Account(mAccountName,"com.google");
  String authToken=getAuthToken(mContext,account);
  if (newToken) {
    AccountManager accountManager=AccountManager.get(mContext);
    accountManager.invalidateAuthToken(account.type,authToken);
    authToken=getAuthToken(mContext,account);
  }
  DefaultHttpClient client=new DefaultHttpClient();
  String continueURL=BASE_URL;
  URI uri=new URI(AUTH_URL + "?continue=" + URLEncoder.encode(continueURL,"UTF-8")+ "&auth="+ authToken);
  HttpGet method=new HttpGet(uri);
  final HttpParams getParams=new BasicHttpParams();
  HttpClientParams.setRedirecting(getParams,false);
  method.setParams(getParams);
  HttpResponse res=client.execute(method);
  Header[] headers=res.getHeaders("Set-Cookie");
  if (res.getStatusLine().getStatusCode() != 302 || headers.length == 0) {
    return res;
  }
  String ascidCookie=null;
  for (  Header header : headers) {
    if (header.getValue().indexOf("ACSID=") >= 0) {
      String value=header.getValue();
      String[] pairs=value.split(";");
      ascidCookie=pairs[0];
    }
  }
  uri=new URI(BASE_URL + urlPath);
  HttpPost post=new HttpPost(uri);
  UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"UTF-8");
  post.setEntity(entity);
  post.setHeader("Cookie",ascidCookie);
  post.setHeader("X-Same-Domain","1");
  res=client.execute(post);
  return res;
}
 

Example 52

From project hsDroid, under directory /src/de/nware/app/hsDroid/provider/.

Source file: onlineService2Provider.java

  15 
vote

/** 
 * Stellt HTTP Anfrage und liefert deren Antwort zur?ck.
 * @param url die formatierte URL
 * @return die HTML/XML Antwort
 * @throws Exception
 */
private synchronized String getResponse(String url){
  final HttpPost httpPost=new HttpPost(url);
  httpPost.addHeader("User-Agent",USER_AGENT);
  CookieSpecBase cookieSpecBase=new BrowserCompatSpec();
  List<Header> cookieHeader=cookieSpecBase.formatCookies(StaticSessionData.cookies);
  httpPost.setHeader(cookieHeader.get(0));
  int connectionTimeoutMillis=Integer.valueOf(StaticSessionData.sPreferences.getString(getContext().getString(R.string.Preference_ConnectionTimeout),"1500"));
  HttpClient client=HttpClientFactory.getHttpClient(connectionTimeoutMillis);
  try {
    final HttpResponse response=client.execute(httpPost);
    final StatusLine status=response.getStatusLine();
    if (status.getStatusCode() != HttpStatus.SC_OK) {
      Log.d(TAG,"http status code: " + status.getStatusCode());
      throw new RuntimeException("Ung?ltige Antwort vom Server: " + status.toString());
    }
    final HttpEntity entity=response.getEntity();
    final InputStream inputStream=entity.getContent();
    final ByteArrayOutputStream content=new ByteArrayOutputStream();
    int readBytes=0;
    while ((readBytes=inputStream.read(mContentBuffer)) != -1) {
      content.write(mContentBuffer,0,readBytes);
    }
    String output=new String(content.toByteArray());
    content.close();
    return output;
  }
 catch (  IOException e) {
    Log.d(TAG,e.getMessage());
    throw new RuntimeException("Verbindung fehlgeschlagen: " + e.getMessage(),e);
  }
}