Java Code Examples for org.apache.http.HttpEntity

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 2Degrees-Toolbox, under directory /Toolbox/src/biz/shadowservices/DegreesToolbox/.

Source file: HttpGetter.java

  33 
vote

public String execute() throws ClientProtocolException, IOException {
  if (response == null) {
    HttpClient httpClient=HttpClientSingleton.getInstance();
    HttpResponse serverresponse=null;
    serverresponse=httpClient.execute(httpget);
    HttpEntity entity=serverresponse.getEntity();
    StringWriter writer=new StringWriter();
    IOUtils.copy(entity.getContent(),writer);
    response=writer.toString();
  }
  return response;
}
 

Example 2

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

Source file: AsyncHttpClient.java

  32 
vote

private HttpEntity paramsToEntity(RequestParams params){
  HttpEntity entity=null;
  if (params != null) {
    entity=params.getEntity();
  }
  return entity;
}
 

Example 3

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

Source file: CommonsHttpOAuthProvider.java

  32 
vote

@Override protected void closeConnection(HttpRequest request,com.nostra13.socialsharing.twitter.extpack.oauth.signpost.http.HttpResponse response) throws Exception {
  if (response != null) {
    HttpEntity entity=((HttpResponse)response.unwrap()).getEntity();
    if (entity != null) {
      try {
        entity.consumeContent();
      }
 catch (      IOException e) {
        e.printStackTrace();
      }
    }
  }
}
 

Example 4

From project androidquery, under directory /demo/src/com/androidquery/test/async/.

Source file: AjaxLoadingActivity.java

  32 
vote

public void async_post_entity() throws UnsupportedEncodingException {
  String url="http://search.twitter.com/search.json";
  List<NameValuePair> pairs=new ArrayList<NameValuePair>();
  pairs.add(new BasicNameValuePair("q","androidquery"));
  HttpEntity entity=new UrlEncodedFormEntity(pairs,"UTF-8");
  Map<String,Object> params=new HashMap<String,Object>();
  params.put(AQuery.POST_ENTITY,entity);
  aq.progress(R.id.progress).ajax(url,params,JSONObject.class,new AjaxCallback<JSONObject>(){
    @Override public void callback(    String url,    JSONObject json,    AjaxStatus status){
      showResult(json,status);
    }
  }
);
}
 

Example 5

From project Android_1, under directory /GsonJsonWebservice/src/com/novoda/activity/.

Source file: JsonRequest.java

  32 
vote

private InputStream retrieveStream(String url){
  DefaultHttpClient client=new DefaultHttpClient();
  HttpGet getRequest=new HttpGet(url);
  try {
    HttpResponse getResponse=client.execute(getRequest);
    final int statusCode=getResponse.getStatusLine().getStatusCode();
    if (statusCode != HttpStatus.SC_OK) {
      Log.w(getClass().getSimpleName(),"Error " + statusCode + " for URL "+ url);
      return null;
    }
    HttpEntity getResponseEntity=getResponse.getEntity();
    return getResponseEntity.getContent();
  }
 catch (  IOException e) {
    getRequest.abort();
    Log.w(getClass().getSimpleName(),"Error for URL " + url,e);
  }
  return null;
}
 

Example 6

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

Source file: WebHelper.java

  32 
vote

private static HttpResponse postHttp(String url,JSONObject jsonObject) throws ClientProtocolException, IOException {
  HttpClient httpclient=new DefaultHttpClient();
  HttpPost httppost=new HttpPost(url);
  httppost.setHeader("User-Agent","immopoly android client " + ImmopolyActivity.getStaticVersionInfo());
  httppost.setHeader("Accept-Encoding","gzip");
  HttpEntity entity;
  entity=new StringEntity(jsonObject.toString());
  httppost.setEntity(entity);
  return httpclient.execute(httppost);
}
 

Example 7

From project apps-for-android, under directory /Panoramio/src/com/google/android/panoramio/.

Source file: ImageManager.java

  32 
vote

@Override public void run(){
  String url=THUMBNAIL_URL;
  url=String.format(url,mMinLat,mMinLong,mMaxLat,mMaxLong);
  try {
    URI uri=new URI("http",url,null);
    HttpGet get=new HttpGet(uri);
    HttpClient client=new DefaultHttpClient();
    HttpResponse response=client.execute(get);
    HttpEntity entity=response.getEntity();
    String str=convertStreamToString(entity.getContent());
    JSONObject json=new JSONObject(str);
    parse(json);
  }
 catch (  Exception e) {
    Log.e(TAG,e.toString());
  }
}
 

Example 8

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

Source file: RequestHandler.java

  32 
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 9

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

Source file: ArtifactoryBuildInfoClient.java

  32 
vote

/** 
 * @return A list of local repositories available for deployment.
 * @throws IOException On any connection error
 */
public List<String> getLocalRepositoriesKeys() throws IOException {
  List<String> repositories=new ArrayList<String>();
  PreemptiveHttpClient client=httpClient.getHttpClient();
  String localReposUrl=artifactoryUrl + LOCAL_REPOS_REST_URL;
  log.debug("Requesting local repositories list from: " + localReposUrl);
  HttpGet httpget=new HttpGet(localReposUrl);
  HttpResponse response=client.execute(httpget);
  StatusLine statusLine=response.getStatusLine();
  HttpEntity entity=response.getEntity();
  if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
    if (entity != null) {
      entity.consumeContent();
    }
    throwHttpIOException("Failed to obtain list of repositories:",statusLine);
  }
 else {
    if (entity != null) {
      repositories=new ArrayList<String>();
      InputStream content=entity.getContent();
      JsonParser parser;
      try {
        parser=httpClient.createJsonParser(content);
        JsonNode result=parser.readValueAsTree();
        log.debug("Repositories result = " + result);
        for (        JsonNode jsonNode : result) {
          String repositoryKey=jsonNode.get("key").getTextValue();
          repositories.add(repositoryKey);
        }
      }
  finally {
        if (content != null) {
          content.close();
        }
      }
    }
  }
  return repositories;
}
 

Example 10

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

Source file: ServerProxyHandler.java

  32 
vote

/** 
 * Get content as a input stream.
 * @param qi the additional client query info
 * @param cp the content producer
 * @return the response input stream
 * @throws Throwable for any error
 */
protected Result getResultWithContentProducer(QueryInfo qi,ContentProducer cp) throws Throwable {
  HttpEntity entity=null;
  if (cp != null) {
    if (allowsStreaming) {
      entity=new EntityTemplate(cp);
    }
 else {
      ByteArrayOutputStream baos=new ByteArrayOutputStream();
      cp.writeTo(baos);
      entity=new ByteArrayEntity(baos.toByteArray());
    }
  }
  return getResultWithHttpEntity(qi,entity);
}
 

Example 11

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

Source file: ActualInfo.java

  32 
vote

private String getStringFromWebDoc(String strDocURL) throws IOException {
  DefaultHttpClient httpclient=new DefaultHttpClient();
  HttpGet httpget=new HttpGet(strDocURL);
  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());
  }
  InputStream inStream=entity.getContent();
  BufferedInputStream inBuffStream=new BufferedInputStream(inStream);
  StringBuffer fileData=new StringBuffer(1000);
  byte[] buf=new byte[1024];
  int numRead=0;
  while ((numRead=inBuffStream.read(buf)) != -1) {
    fileData.append(new String(buf),0,numRead);
  }
  inBuffStream.close();
  return fileData.toString();
}
 

Example 12

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

Source file: InternalResponse.java

  32 
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 13

From project couchdb-lucene, under directory /src/main/java/com/github/rnewson/couchdb/lucene/util/.

Source file: ErrorPreservingResponseHandler.java

  32 
vote

public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
  final StatusLine statusLine=response.getStatusLine();
  final HttpEntity entity=response.getEntity();
  final String str=entity == null ? null : EntityUtils.toString(entity);
  if (statusLine.getStatusCode() >= 300) {
    throw new HttpResponseException(statusLine.getStatusCode(),str);
  }
  return str;
}
 

Example 14

From project cw-android, under directory /Service/Downloader/src/com/commonsware/android/downloader/.

Source file: ByteArrayResponseHandler.java

  32 
vote

public byte[] handleResponse(final HttpResponse response) throws IOException, HttpResponseException {
  StatusLine statusLine=response.getStatusLine();
  if (statusLine.getStatusCode() >= 300) {
    throw new HttpResponseException(statusLine.getStatusCode(),statusLine.getReasonPhrase());
  }
  HttpEntity entity=response.getEntity();
  if (entity == null) {
    return (null);
  }
  return (EntityUtils.toByteArray(entity));
}
 

Example 15

From project cw-omnibus, under directory /Power/Downloader/src/com/commonsware/android/tuning/downloader/.

Source file: ByteArrayResponseHandler.java

  32 
vote

public byte[] handleResponse(final HttpResponse response) throws IOException, HttpResponseException {
  StatusLine statusLine=response.getStatusLine();
  if (statusLine.getStatusCode() >= 300) {
    throw new HttpResponseException(statusLine.getStatusCode(),statusLine.getReasonPhrase());
  }
  HttpEntity entity=response.getEntity();
  if (entity == null) {
    return (null);
  }
  return (EntityUtils.toByteArray(entity));
}
 

Example 16

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

Source file: BetterHttp.java

  32 
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 17

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

Source file: DefaultHttpClientWrapper.java

  32 
vote

public static String getResponseBody(HttpResponse resp) throws HTTPException {
  HttpEntity entity=resp.getEntity();
  InputStream is=getUnpackedInputStream(entity);
  try {
    return IOUtils.readAndCloseInputStream(is);
  }
 catch (  Exception e) {
    throw new HTTPException(e);
  }
}
 

Example 18

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

Source file: SocialJSONDecodingSupport.java

  32 
vote

/** 
 * Parse JSON text into java Model object from the input source. and then it's base on the class type.
 * @param < T > Generic type must extend from Model.
 * @param clazz Class type.
 * @param response HttpResponse which getting the JSONContent.
 * @throws ParseException Throw this exception if any
 * @throws IOException Throw this exception if any
 */
public static <T extends Model>T parser(final Class<T> clazz,HttpResponse response) throws IOException, ParseException {
  HttpEntity entity=SocialHttpClientSupport.processContent(response);
  if (entity.getContentLength() != -1) {
    String jsonContent=EntityUtils.toString(entity);
    SocialHttpClientSupport.consume(entity);
    return parser(clazz,jsonContent);
  }
 else {
    return null;
  }
}
 

Example 19

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

Source file: HttpClient.java

  32 
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 20

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

Source file: GZipInterceptor.java

  32 
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 21

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

Source file: ContentEncoding.java

  32 
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 22

From project httpClient, under directory /fluent-hc/src/main/java/org/apache/http/client/fluent/.

Source file: ContentResponseHandler.java

  32 
vote

public Content handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
  StatusLine statusLine=response.getStatusLine();
  HttpEntity entity=response.getEntity();
  if (statusLine.getStatusCode() >= 300) {
    throw new HttpResponseException(statusLine.getStatusCode(),statusLine.getReasonPhrase());
  }
  if (entity != null) {
    return new Content(EntityUtils.toByteArray(entity),ContentType.getOrDefault(entity));
  }
 else {
    return Content.NO_CONTENT;
  }
}
 

Example 23

From project accounted4, under directory /accounted4/stock-quote/stock-quote-yahoo/src/main/java/com/accounted4/stockquote/yahoo/.

Source file: YahooQuoteService.java

  31 
vote

@Override public List<HashMap<QuoteAttribute,String>> executeQuery(List<String> securityList,List<QuoteAttribute> quoteAttributes){
  String tickerList=securityListToString(securityList);
  String attributeList=attributeListToString(quoteAttributes);
  HttpClient httpclient=new DefaultHttpClient();
  String urlString=BASE_URL + "?" + "s="+ tickerList+ "&"+ "f="+ attributeList;
  System.out.println("Query url: " + urlString);
  HttpGet httpGet=new HttpGet(urlString);
  try {
    HttpResponse response=httpclient.execute(httpGet);
    HttpEntity entity=response.getEntity();
    if (entity != null) {
      String stringResponse=EntityUtils.toString(entity);
      return processResponse(stringResponse,quoteAttributes);
    }
  }
 catch (  IOException ex) {
    System.out.println("Error " + ex);
  }
  List<HashMap<QuoteAttribute,String>> result=new ArrayList<>();
  return result;
}
 

Example 24

From project adg-android, under directory /src/com/analysedesgeeks/android/service/impl/.

Source file: DownloadServiceImpl.java

  31 
vote

@Override public boolean downloadFeed(){
  boolean downloadSuccess=false;
  if (connectionService.isConnected()) {
    InputStream inputStream=null;
    try {
      final HttpGet httpget=new HttpGet(new URI(Const.FEED_URL));
      final HttpResponse response=new DefaultHttpClient().execute(httpget);
      final StatusLine status=response.getStatusLine();
      if (status.getStatusCode() != HttpStatus.SC_OK) {
        Ln.e("Erreur lors du t??hargement:%s,%s",status.getStatusCode(),status.getReasonPhrase());
      }
 else {
        final HttpEntity entity=response.getEntity();
        inputStream=entity.getContent();
        final ByteArrayOutputStream content=new ByteArrayOutputStream();
        int readBytes=0;
        final byte[] sBuffer=new byte[512];
        while ((readBytes=inputStream.read(sBuffer)) != -1) {
          content.write(sBuffer,0,readBytes);
        }
        final String dataAsString=new String(content.toByteArray());
        final List<FeedItem> syndFeed=rssService.parseRss(dataAsString);
        if (syndFeed != null) {
          databaseService.save(dataAsString);
          downloadSuccess=true;
        }
      }
    }
 catch (    final Throwable t) {
      Ln.e(t);
    }
 finally {
      closeQuietly(inputStream);
    }
  }
  return downloadSuccess;
}
 

Example 25

From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/util/http/.

Source file: HttpBuilder.java

  31 
vote

private <T>HttpResult<T> doPost(Type target){
  try {
    URI path=createPath(address);
    HttpPost post=new HttpPost(path);
    HttpEntity entity=prepareMultipart();
    post.setEntity(entity);
    return doRequest(post,target);
  }
 catch (  UnsupportedEncodingException e) {
    Log.e(Constants.TAG,"Couldn't process parameters",e);
    return error();
  }
catch (  URISyntaxException e) {
    Log.e(Constants.TAG,"Couldn't create path",e);
    return error();
  }
}
 

Example 26

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

Source file: ApacheHttpClient.java

  31 
vote

@Override public InputStream getInputStream() throws IOException {
  if (countingInputStream == null) {
    HttpEntity entity=response.getEntity();
    if (entity != null) {
      InputStream content=entity.getContent();
      if (content != null) {
        countingInputStream=new CountingInputStream(content);
      }
    }
  }
  if (countingInputStream == null) {
    throw new IOException("No input stream");
  }
  return countingInputStream;
}
 

Example 27

From project ajah, under directory /ajah-http/src/main/java/com/ajah/http/.

Source file: Http.java

  31 
vote

private static HttpEntity internalGet(final URI uri) throws IOException, ClientProtocolException, NotFoundException, UnexpectedResponseCode {
  final HttpClient httpclient=new DefaultHttpClient();
  final HttpGet httpget=new HttpGet(uri);
  final HttpResponse response=httpclient.execute(httpget);
  if (response.getStatusLine().getStatusCode() == 200) {
    final HttpEntity entity=response.getEntity();
    return entity;
  }
 else   if (response.getStatusLine().getStatusCode() == 404) {
    throw new NotFoundException(response.getStatusLine().getStatusCode() + " - " + response.getStatusLine().getReasonPhrase());
  }
 else {
    throw new UnexpectedResponseCode(response.getStatusLine().getStatusCode() + " - " + response.getStatusLine().getReasonPhrase());
  }
}
 

Example 28

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

Source file: HttpClient4.java

  31 
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 29

From project android-bankdroid, under directory /src/com/liato/bankdroid/banking/banks/.

Source file: Chalmrest.java

  31 
vote

@Override public void update() throws BankException, LoginException, BankChoiceException {
  super.update();
  if (username == null || username.length() == 0)   throw new LoginException(res.getText(R.string.invalid_username_password).toString());
  try {
    String cardNr=username;
    HttpClient httpclient=new DefaultHttpClient();
    HttpGet httpget=new HttpGet("http://kortladdning.chalmerskonferens.se/bgw.aspx?type=getCardAndArticles&card=" + cardNr);
    HttpResponse response=httpclient.execute(httpget);
    HttpEntity entity=response.getEntity();
    if (entity == null)     throw new BankException("Couldn't connect!");
    String s1=EntityUtils.toString(entity);
    Pattern pattern=Pattern.compile("<ExtendedInfo Name=\"Kortvarde\" Type=\"System.Double\" >(.*?)</ExtendedInfo>");
    Matcher matcher=pattern.matcher(s1);
    if (!matcher.find())     throw new BankException("Couldn't parse value!");
    String value=matcher.group(1);
    StringBuilder sb=new StringBuilder();
    int last=0;
    Matcher match=Pattern.compile("_x([0-9A-Fa-f]{4})_").matcher(value);
    while (match.find()) {
      sb.append(value.substring(last,Math.max(match.start() - 1,0)));
      int i=Integer.parseInt(match.group(1),16);
      sb.append((char)i);
      last=match.end();
    }
    sb.append(value.substring(last));
    value=sb.toString();
    matcher=Pattern.compile("<CardInfo id=\"" + cardNr + "\" Name=\"(.*?)\"").matcher(s1);
    if (!matcher.find())     throw new BankException("Coldn't parse name!");
    String name=matcher.group(1);
    accounts.add(new Account(name,BigDecimal.valueOf(Double.parseDouble(value)),"1"));
  }
 catch (  Exception e) {
    throw new BankException(e.getMessage());
  }
 finally {
    super.updateComplete();
  }
}
 

Example 30

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

Source file: HttpBundle.java

  31 
vote

public String getResponseText(){
  HttpEntity responseEntity=response.getEntity();
  StringBuilder result=new StringBuilder();
  HeaderIterator itr=response.headerIterator();
  while (itr.hasNext()) {
    result.append(itr.nextHeader() + "\n");
  }
  String xml="\n\n";
  try {
    xml=EntityUtils.toString(responseEntity);
  }
 catch (  ParseException e1) {
    e1.printStackTrace();
  }
catch (  IOException e1) {
    e1.printStackTrace();
  }
  result.append(xml);
  return result.toString();
}
 

Example 31

From project android-rss, under directory /src/main/java/org/mcsoxford/rss/.

Source file: RSSReader.java

  31 
vote

/** 
 * Send HTTP GET request and parse the XML response to construct an in-memory representation of an RSS 2.0 feed.
 * @param uri RSS 2.0 feed URI
 * @return in-memory representation of downloaded RSS feed
 * @throws RSSReaderException if RSS feed could not be retrieved because ofHTTP error
 * @throws RSSFault if an unrecoverable IO error has occurred
 */
public RSSFeed load(String uri) throws RSSReaderException {
  final HttpGet httpget=new HttpGet(uri);
  InputStream feedStream=null;
  try {
    final HttpResponse response=httpclient.execute(httpget);
    final StatusLine status=response.getStatusLine();
    if (status.getStatusCode() != HttpStatus.SC_OK) {
      throw new RSSReaderException(status.getStatusCode(),status.getReasonPhrase());
    }
    HttpEntity entity=response.getEntity();
    feedStream=entity.getContent();
    RSSFeed feed=parser.parse(feedStream);
    if (feed.getLink() == null) {
      feed.setLink(android.net.Uri.parse(uri));
    }
    return feed;
  }
 catch (  ClientProtocolException e) {
    throw new RSSFault(e);
  }
catch (  IOException e) {
    throw new RSSFault(e);
  }
 finally {
    Resources.closeQuietly(feedStream);
  }
}
 

Example 32

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

Source file: WebClient.java

  31 
vote

public synchronized String getUrlContent(String url) 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);
  HttpGet request=new HttpGet(uri.getPath());
  request.setHeader("User-Agent",sUserAgent);
  try {
    HttpResponse response=client.execute(host,request);
    StatusLine status=response.getStatusLine();
    Log.i(cTag,"get with response " + status.toString());
    if (status.getStatusCode() != HttpStatus.SC_OK) {
      throw new ApiException("Invalid response from server: " + status.toString());
    }
    HttpEntity entity=response.getEntity();
    InputStream inputStream=entity.getContent();
    ByteArrayOutputStream content=new ByteArrayOutputStream();
    int readBytes;
    while ((readBytes=inputStream.read(sBuffer)) != -1) {
      content.write(sBuffer,0,readBytes);
    }
    return new String(content.toByteArray());
  }
 catch (  IOException e) {
    throw new ApiException("Problem communicating with API",e);
  }
}
 

Example 33

From project Android-SyncAdapter-JSON-Server-Example, under directory /src/com/example/android/samplesync/client/.

Source file: NetworkUtilities.java

  31 
vote

/** 
 * Fetches the list of friend data updates from the server
 * @param account The account being synced.
 * @param authtoken The authtoken stored in AccountManager for this account
 * @param lastUpdated The last time that sync was performed
 * @return list The list of updates received from the server.
 */
public static List<User> fetchFriendUpdates(Account account,String authtoken,Date lastUpdated) throws JSONException, ParseException, IOException, AuthenticationException {
  final ArrayList<User> friendList=new ArrayList<User>();
  final ArrayList<NameValuePair> params=new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair(PARAM_USERNAME,account.name));
  params.add(new BasicNameValuePair(PARAM_PASSWORD,authtoken));
  if (lastUpdated != null) {
    final SimpleDateFormat formatter=new SimpleDateFormat("yyyy/MM/dd HH:mm");
    formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    params.add(new BasicNameValuePair(PARAM_UPDATED,formatter.format(lastUpdated)));
  }
  Log.i(TAG,params.toString());
  HttpEntity entity=null;
  entity=new UrlEncodedFormEntity(params);
  final HttpPost post=new HttpPost(FETCH_FRIEND_UPDATES_URI);
  post.addHeader(entity.getContentType());
  post.setEntity(entity);
  maybeCreateHttpClient();
  final HttpResponse resp=mHttpClient.execute(post);
  final String response=EntityUtils.toString(resp.getEntity());
  if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    final JSONArray friends=new JSONArray(response);
    Log.d(TAG,response);
    for (int i=0; i < friends.length(); i++) {
      friendList.add(User.valueOf(friends.getJSONObject(i)));
    }
  }
 else {
    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
      Log.e(TAG,"Authentication exception in fetching remote contacts");
      throw new AuthenticationException();
    }
 else {
      Log.e(TAG,"Server error in fetching remote contacts: " + resp.getStatusLine());
      throw new IOException();
    }
  }
  return friendList;
}
 

Example 34

From project android-tether, under directory /src/og/android/tether/system/.

Source file: WebserviceTask.java

  31 
vote

public static void report(String url,HashMap<String,Object> paramMap){
  List<BasicNameValuePair> params=new ArrayList<BasicNameValuePair>();
  Set<Entry<String,Object>> a=paramMap.entrySet();
  for (  Entry<String,Object> e : a) {
    Object o=e.getValue();
    if (o != null) {
      params.add(new BasicNameValuePair(e.getKey(),o.toString()));
    }
  }
  try {
    HttpResponse response=makeRequest(url,params);
    StatusLine status=response.getStatusLine();
    Log.d(MSG_TAG,"Request returned status " + status);
    if (status.getStatusCode() == 200) {
      HttpEntity entity=response.getEntity();
      Log.d(MSG_TAG,"Request returned: " + entity.getContent());
    }
  }
 catch (  Exception e) {
    Log.d(MSG_TAG,"Can't report stats '" + url + "' ("+ e.toString()+ ").");
  }
}
 

Example 35

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

Source file: BooksStore.java

  31 
vote

/** 
 * Executes an HTTP request on a REST web service. If the response is ok, the content is sent to the specified response handler.
 * @param host
 * @param get The GET request to executed.
 * @param handler The handler which will parse the response.
 * @throws java.io.IOException
 */
private void executeRequest(HttpHost host,HttpGet get,ResponseHandler handler) throws IOException {
  HttpEntity entity=null;
  try {
    final HttpResponse response=HttpManager.execute(host,get);
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
      entity=response.getEntity();
      final InputStream in=entity.getContent();
      handler.handleResponse(in);
    }
  }
  finally {
    if (entity != null) {
      entity.consumeContent();
    }
  }
}
 

Example 36

From project android_packages_apps_Gallery3D, under directory /src/com/cooliris/media/.

Source file: UriTexture.java

  31 
vote

private static final BufferedInputStream createInputStreamFromRemoteUrl(String uri,ClientConnectionManager connectionManager){
  InputStream contentInput=null;
  if (connectionManager == null) {
    try {
      URL url=new URI(uri).toURL();
      URLConnection conn=url.openConnection();
      conn.connect();
      contentInput=conn.getInputStream();
    }
 catch (    Exception e) {
      Log.w(TAG,"Request failed: " + uri);
      e.printStackTrace();
      return null;
    }
  }
 else {
    final DefaultHttpClient mHttpClient=new DefaultHttpClient(connectionManager,HTTP_PARAMS);
    HttpUriRequest request=new HttpGet(uri);
    HttpResponse httpResponse=null;
    try {
      httpResponse=mHttpClient.execute(request);
      HttpEntity entity=httpResponse.getEntity();
      if (entity != null) {
        contentInput=entity.getContent();
      }
    }
 catch (    Exception e) {
      Log.w(TAG,"Request failed: " + request.getURI());
      return null;
    }
  }
  if (contentInput != null) {
    return new BufferedInputStream(contentInput,4096);
  }
 else {
    return null;
  }
}
 

Example 37

From project Anki-Android, under directory /src/com/ichi2/anki/.

Source file: AnkiDroidProxy.java

  31 
vote

public String getDecks(){
  String decksServer="{}";
  try {
    String data="p=" + URLEncoder.encode(mPassword,"UTF-8") + "&client=ankidroid-0.4&u="+ URLEncoder.encode(mUsername,"UTF-8")+ "&d=None&sources="+ URLEncoder.encode("[]","UTF-8")+ "&libanki=0.9.9.8.6&pversion=5";
    HttpPost httpPost=new HttpPost(SYNC_URL + "getDecks");
    StringEntity entity=new StringEntity(data);
    httpPost.setEntity(entity);
    httpPost.setHeader("Accept-Encoding","identity");
    httpPost.setHeader("Content-type","application/x-www-form-urlencoded");
    DefaultHttpClient httpClient=new DefaultHttpClient();
    HttpResponse response=httpClient.execute(httpPost);
    Log.i(AnkiDroidApp.TAG,"Response = " + response.toString());
    HttpEntity entityResponse=response.getEntity();
    Log.i(AnkiDroidApp.TAG,"Entity's response = " + entityResponse.toString());
    InputStream content=entityResponse.getContent();
    Log.i(AnkiDroidApp.TAG,"Content = " + content.toString());
    decksServer=Utils.convertStreamToString(new InflaterInputStream(content));
    Log.i(AnkiDroidApp.TAG,"String content = " + decksServer);
  }
 catch (  UnsupportedEncodingException e) {
    e.printStackTrace();
  }
catch (  ClientProtocolException e) {
    Log.i(AnkiDroidApp.TAG,"ClientProtocolException = " + e.getMessage());
  }
catch (  IOException e) {
    Log.i(AnkiDroidApp.TAG,"IOException = " + e.getMessage());
  }
  return decksServer;
}
 

Example 38

From project anode, under directory /app/src/org/meshpoint/anode/util/.

Source file: ModuleUtils.java

  31 
vote

public static File getResource(URI httpUri,String filename) throws IOException {
  HttpClient http=new DefaultHttpClient();
  HttpGet request=new HttpGet();
  request.setURI(httpUri);
  HttpEntity entity=http.execute(request).getEntity();
  InputStream in=entity.getContent();
  File destination=new File(resourceDir,filename);
  FileOutputStream out=new FileOutputStream(destination);
  byte[] buf=new byte[1024];
  int read;
  while ((read=in.read(buf)) != -1) {
    out.write(buf,0,read);
  }
  in.close();
  out.flush();
  out.close();
  return destination;
}
 

Example 39

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

Source file: SyncService.java

  31 
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 40

From project aranea, under directory /webapp/src/test/java/no/dusken/aranea/integration/test/.

Source file: AbstractIntegrationTest.java

  31 
vote

private void checkValidity(){
  try {
    HttpPost post=new HttpPost("http://validator.w3.org/check");
    List<NameValuePair> formparams=new ArrayList<NameValuePair>();
    String pageSource=webDriver.getPageSource();
    formparams.add(new BasicNameValuePair("fragment",pageSource));
    formparams.add(new BasicNameValuePair("output","json"));
    UrlEncodedFormEntity entity=new UrlEncodedFormEntity(formparams,"UTF-8");
    post.setEntity(entity);
    HttpResponse httpResponse=httpclient.execute(post);
    HttpEntity responseEntity=httpResponse.getEntity();
    Map values=mapper.readValue(responseEntity.getContent(),Map.class);
    checkValues((List<Map<String,Object>>)values.get("messages"));
  }
 catch (  IOException e) {
    fail("Error when checking validity: " + e.getMessage());
    e.printStackTrace();
  }
}
 

Example 41

From project AudioBox.fm-JavaLib, under directory /audiobox.fm-core/src/main/java/fm/audiobox/configurations/.

Source file: DefaultRequestMethod.java

  31 
vote

@Override public Response send(boolean async,List<NameValuePair> params) throws ServiceException, LoginException {
  HttpEntity entity=null;
  if ((!isGET() && !isDELETE()) && params != null) {
    try {
      if (log.isInfoEnabled()) {
        StringBuffer sb=new StringBuffer();
        for (        NameValuePair param : params) {
          sb.append("[" + param.getName() + ": '"+ param.getValue()+ "'], ");
        }
        log.info("Params: " + sb.toString());
      }
      entity=new UrlEncodedFormEntity(params,HTTP.UTF_8);
    }
 catch (    UnsupportedEncodingException e) {
      log.error("An error occurred while instantiating UrlEncodedFormEntity",e);
    }
  }
  return send(async,entity);
}
 

Example 42

From project azure4j-blog-samples, under directory /ACSManagementService/src/com/persistent/azure/acs/.

Source file: ACSAuthenticationHelper.java

  31 
vote

/** 
 * Get OAuth SWT token from ACS
 */
private String getTokenFromACS(String acsNamespace,String acsMgmtPassword){
  try {
    DefaultHttpClient httpClient=new DefaultHttpClient();
    HttpPost httpPost=new HttpPost(String.format(ACSAuthenticationHelper.AcsTokenServiceUrl,acsNamespace));
    List<NameValuePair> listNameValuePairs=new ArrayList<NameValuePair>();
    listNameValuePairs.add(new BasicNameValuePair("grant_type","client_credentials"));
    listNameValuePairs.add(new BasicNameValuePair("client_id",managementUserName));
    listNameValuePairs.add(new BasicNameValuePair("client_secret",acsMgmtPassword));
    listNameValuePairs.add(new BasicNameValuePair("scope",String.format(ACSAuthenticationHelper.AcsODataServiceUrl,acsNamespace)));
    UrlEncodedFormEntity formEntity=new UrlEncodedFormEntity(listNameValuePairs);
    httpPost.setEntity(formEntity);
    HttpResponse httpResponse=httpClient.execute(httpPost);
    HttpEntity entity=httpResponse.getEntity();
    InputStream inputStream=entity.getContent();
    InputStreamReader streamReader=new InputStreamReader(inputStream);
    BufferedReader bufferedReader=new BufferedReader(streamReader);
    String string=null;
    StringBuffer response=new StringBuffer();
    while ((string=bufferedReader.readLine()) != null) {
      response.append(string);
    }
    JSONObject obj=new JSONObject(response.toString());
    return obj.getString("access_token");
  }
 catch (  Exception e) {
    e.printStackTrace();
    return null;
  }
}
 

Example 43

From project BBC-News-Reader, under directory /src/org/mcsoxford/rss/.

Source file: RSSReader.java

  31 
vote

/** 
 * Send HTTP GET request and parse the XML response to construct an in-memory representation of an RSS 2.0 feed.
 * @param uri RSS 2.0 feed URI
 * @return in-memory representation of downloaded RSS feed
 * @throws RSSReaderException if RSS feed could not be retrieved because ofHTTP error
 * @throws RSSFault if an unrecoverable IO error has occurred
 */
public RSSFeed load(String uri) throws RSSReaderException {
  final HttpGet httpget=new HttpGet(uri);
  InputStream feed=null;
  try {
    final HttpResponse response=httpclient.execute(httpget);
    final StatusLine status=response.getStatusLine();
    if (status.getStatusCode() != HttpStatus.SC_OK) {
      throw new RSSReaderException(status.getStatusCode(),status.getReasonPhrase());
    }
    HttpEntity entity=response.getEntity();
    feed=entity.getContent();
    return parser.parse(feed);
  }
 catch (  ClientProtocolException e) {
    throw new RSSFault(e);
  }
catch (  IOException e) {
    throw new RSSFault(e);
  }
 finally {
    Resources.closeQuietly(feed);
  }
}
 

Example 44

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

Source file: SyncService.java

  31 
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 45

From project beintoo-android-sdk, under directory /BeintooSDK/src/com/beintoo/beintoosdkutility/.

Source file: LoaderImageView.java

  31 
vote

private static Drawable getDrawableFromUrl(final String url) throws IOException, MalformedURLException {
  try {
    HttpGet httpRequest=new HttpGet(new URL(url).toURI());
    HttpClient httpClient=new DefaultHttpClient();
    HttpResponse response=(HttpResponse)httpClient.execute(httpRequest);
    HttpEntity entity=response.getEntity();
    BufferedHttpEntity bufHttpEntity=new BufferedHttpEntity(entity);
    final long contentLength=bufHttpEntity.getContentLength();
    if (contentLength >= 0) {
      InputStream is=bufHttpEntity.getContent();
      return Drawable.createFromStream(is,"name");
    }
 else {
      return null;
    }
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 46

From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/goodreads/.

Source file: GoodreadsManager.java

  31 
vote

/** 
 * Utility routine called to sign a request and submit it then return the raw text output.
 * @author Philip Warner
 * @throws OAuthCommunicationException 
 * @throws OAuthExpectationFailedException 
 * @throws OAuthMessageSignerException 
 * @throws IOException 
 * @throws ClientProtocolException 
 * @throws NotAuthorizedException 
 * @throws BookNotFoundException 
 * @throws NetworkException 
 */
public String executeRaw(HttpUriRequest request) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, ClientProtocolException, IOException, NotAuthorizedException, BookNotFoundException, NetworkException {
  HttpClient httpClient=newHttpClient();
  m_consumer.setTokenWithSecret(m_accessToken,m_accessSecret);
  m_consumer.sign(request);
  waitUntilRequestAllowed();
  HttpResponse response=null;
  try {
    response=httpClient.execute(request);
  }
 catch (  Exception e) {
    throw new NetworkException(e);
  }
  int code=response.getStatusLine().getStatusCode();
  StringBuilder html=new StringBuilder();
  HttpEntity e=response.getEntity();
  if (e != null) {
    InputStream in=e.getContent();
    if (in != null) {
      while (true) {
        int i=in.read();
        if (i == -1)         break;
        html.append((char)(i));
      }
    }
  }
  if (code == 200 || code == 201) {
    return html.toString();
  }
 else   if (code == 401) {
    m_hasValidCredentials=false;
    throw new NotAuthorizedException(null);
  }
 else   if (code == 404) {
    throw new BookNotFoundException(null);
  }
 else {
    throw new RuntimeException("Unexpected status code from API: " + response.getStatusLine().getStatusCode() + "/"+ response.getStatusLine().getReasonPhrase());
  }
}
 

Example 47

From project CityBikes, under directory /src/net/homelinux/penecoptero/android/citybikes/app/.

Source file: RESTHelper.java

  31 
vote

public String restGET(String url) throws ClientProtocolException, IOException, HttpException {
  DefaultHttpClient httpclient=new DefaultHttpClient();
  if (this.authenticated) {
    httpclient=this.setCredentials(httpclient,url);
  }
  HttpGet httpmethod=new HttpGet(url);
  HttpResponse response;
  String result=null;
  try {
    response=httpclient.execute(httpmethod);
    HttpEntity entity=response.getEntity();
    if (entity != null) {
      InputStream instream=entity.getContent();
      result=convertStreamToString(instream);
      instream.close();
    }
  }
 catch (  ClientProtocolException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
  return result;
}
 

Example 48

From project cloudify, under directory /rest-client/src/main/java/org/cloudifysource/restclient/.

Source file: GSRestClient.java

  31 
vote

/** 
 * Gets the HTTP response's body as a String.
 * @param response   The HttpResponse object to analyze
 * @param httpMethod The HTTP request that originated this response
 * @return the body of the given HttpResponse object, as a string
 * @throws ErrorStatusException Reporting a communication failure
 * @throws IOException          Reporting a failure to read the response's content
 */
public static String getResponseBody(final HttpResponse response,final HttpRequestBase httpMethod) throws ErrorStatusException, IOException {
  InputStream instream=null;
  try {
    final HttpEntity entity=response.getEntity();
    if (entity == null) {
      final ErrorStatusException e=new ErrorStatusException(REASON_CODE_COMM_ERR,httpMethod.getURI(),MSG_RESPONSE_ENTITY_NULL);
      logger.log(Level.FINE,MSG_RESPONSE_ENTITY_NULL,e);
      throw e;
    }
    instream=entity.getContent();
    return StringUtils.getStringFromStream(instream);
  }
  finally {
    if (instream != null) {
      try {
        instream.close();
      }
 catch (      final IOException e) {
      }
    }
  }
}
 

Example 49

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

Source file: SyncService.java

  31 
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 50

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

Source file: CouchResponse.java

  31 
vote

/** 
 * C-tor parses the method results to build the CouchResponse object. First, it reads the body (hence the IOException) from the method Next, it checks the status codes to determine if the request was successful. If there was an error, it parses the error codes.
 * @param method
 * @throws IOException
 */
CouchResponse(HttpRequestBase req,HttpResponse response) throws IOException {
  headers=response.getAllHeaders();
  HttpEntity entity=response.getEntity();
  body=EntityUtils.toString(entity);
  path=req.getURI().getPath();
  statusCode=response.getStatusLine().getStatusCode();
  boolean isGet=(req instanceof HttpGet);
  boolean isPut=(req instanceof HttpPut);
  boolean isPost=(req instanceof HttpPost);
  boolean isDelete=(req instanceof HttpDelete);
  if ((isGet && statusCode == 404) || (isPut && statusCode == 409) || (isPost && statusCode == 404)|| (isDelete && statusCode == 404)) {
    JSONObject jbody=JSONObject.fromObject(body);
    error_id=jbody.getString("error");
    error_reason=jbody.getString("reason");
  }
 else   if ((isPut && statusCode == 201) || (isPost && statusCode == 201) || (isDelete && statusCode == 202)|| (isDelete && statusCode == 200)) {
    if (path.endsWith("_bulk_docs")) {
      ok=JSONArray.fromObject(body).size() > 0;
    }
 else {
      ok=JSONObject.fromObject(body).getBoolean("ok");
    }
  }
 else   if ((req instanceof HttpGet) || ((req instanceof HttpPost) && statusCode == 200)) {
    ok=true;
  }
  log.debug(toString());
}
 

Example 51

From project cow, under directory /src/com/ad/cow/library/.

Source file: JSONParser.java

  31 
vote

public JSONObject getJSONFromUrl(String url,List<NameValuePair> params){
  try {
    DefaultHttpClient httpClient=new DefaultHttpClient();
    HttpPost httpPost=new HttpPost(url);
    httpPost.setEntity(new UrlEncodedFormEntity(params));
    HttpResponse httpResponse=httpClient.execute(httpPost);
    HttpEntity httpEntity=httpResponse.getEntity();
    is=httpEntity.getContent();
  }
 catch (  UnsupportedEncodingException e) {
    e.printStackTrace();
  }
catch (  ClientProtocolException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
  try {
    BufferedReader reader=new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
    StringBuilder sb=new StringBuilder();
    String line=null;
    while ((line=reader.readLine()) != null) {
      sb.append(line + "n");
    }
    is.close();
    json=sb.toString();
    Log.e("JSON",json);
  }
 catch (  Exception e) {
    Log.e("Buffer Error","Error converting result " + e.toString());
  }
  try {
    jObj=new JSONObject(json);
  }
 catch (  JSONException e) {
    Log.e("JSON Parser","Error parsing data " + e.toString());
  }
  return jObj;
}
 

Example 52

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

Source file: SyncService.java

  31 
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 53

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

Source file: SyncService.java

  31 
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 54

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

Source file: RestService.java

  31 
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 55

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

Source file: NetworkHelper.java

  31 
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 56

From project DTE, under directory /src/cl/nic/dte/net/.

Source file: ConexionSii.java

  31 
vote

private RECEPCIONDTEDocument uploadEnvio(String rutEnvia,String rutCompania,File archivoEnviarSII,String token,String urlEnvio,String hostEnvio) throws ClientProtocolException, IOException, org.apache.http.ParseException, XmlException {
  HttpClient httpclient=new DefaultHttpClient();
  HttpPost httppost=new HttpPost(urlEnvio);
  MultipartEntity reqEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
  reqEntity.addPart("rutSender",new StringBody(rutEnvia.substring(0,rutEnvia.length() - 2)));
  reqEntity.addPart("dvSender",new StringBody(rutEnvia.substring(rutEnvia.length() - 1,rutEnvia.length())));
  reqEntity.addPart("rutCompany",new StringBody(rutCompania.substring(0,(rutCompania).length() - 2)));
  reqEntity.addPart("dvCompany",new StringBody(rutCompania.substring(rutCompania.length() - 1,rutCompania.length())));
  FileBody bin=new FileBody(archivoEnviarSII);
  reqEntity.addPart("archivo",bin);
  httppost.setEntity(reqEntity);
  BasicClientCookie cookie=new BasicClientCookie("TOKEN",token);
  cookie.setPath("/");
  cookie.setDomain(hostEnvio);
  cookie.setSecure(true);
  cookie.setVersion(1);
  CookieStore cookieStore=new BasicCookieStore();
  cookieStore.addCookie(cookie);
  httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.RFC_2109);
  httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.BROWSER_COMPATIBILITY);
  HttpContext localContext=new BasicHttpContext();
  localContext.setAttribute(ClientContext.COOKIE_STORE,cookieStore);
  httppost.addHeader(new BasicHeader("User-Agent",Utilities.netLabels.getString("UPLOAD_SII_HEADER_VALUE")));
  HttpResponse response=httpclient.execute(httppost,localContext);
  HttpEntity resEntity=response.getEntity();
  RECEPCIONDTEDocument resp=null;
  HashMap<String,String> namespaces=new HashMap<String,String>();
  namespaces.put("","http://www.sii.cl/SiiDte");
  XmlOptions opts=new XmlOptions();
  opts.setLoadSubstituteNamespaces(namespaces);
  resp=RECEPCIONDTEDocument.Factory.parse(EntityUtils.toString(resEntity),opts);
  return resp;
}
 

Example 57

From project E12Planner, under directory /src/com/neoware/rss/.

Source file: RSSReader.java

  31 
vote

/** 
 * Send HTTP GET request and parse the XML response to construct an in-memory representation of an RSS 2.0 feed.
 * @param uri RSS 2.0 feed URI
 * @return in-memory representation of downloaded RSS feed
 * @throws RSSReaderException if RSS feed could not be retrieved because ofHTTP error
 * @throws RSSFault if an unrecoverable IO error has occurred
 */
public RSSFeed load(String uri) throws RSSReaderException {
  final HttpGet httpget=new HttpGet(uri);
  InputStream feedStream=null;
  try {
    final HttpResponse response=httpclient.execute(httpget);
    final StatusLine status=response.getStatusLine();
    if (status.getStatusCode() != HttpStatus.SC_OK) {
      throw new RSSReaderException(status.getStatusCode(),status.getReasonPhrase());
    }
    HttpEntity entity=response.getEntity();
    feedStream=entity.getContent();
    RSSFeed feed=parser.parse(feedStream);
    if (feed.getLink() == null) {
      feed.setLink(android.net.Uri.parse(uri));
    }
    return feed;
  }
 catch (  ClientProtocolException e) {
    throw new RSSFault(e);
  }
catch (  IOException e) {
    throw new RSSFault(e);
  }
 finally {
    Resources.closeQuietly(feedStream);
  }
}
 

Example 58

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

Source file: NuxeoRegistrationService.java

  31 
vote

/** 
 * Queries nuxeo docs
 * @param query Query to send
 * @return The response send back by Nuxeo
 * @throws Exception 
 */
public String sendQuery(String query) throws Exception {
  StringBuffer urlBuf=new StringBuffer(PropertyManager.getPropertyManager().getProperty("nuxeo.automation.service"));
  urlBuf.append("Document.Query");
  try {
    JSONObject bodyBuf=new JSONObject();
    JSONObject bodyBufQuery=new JSONObject();
    bodyBufQuery.put("query",query);
    bodyBuf.put("params",bodyBufQuery);
    logger.debug("[sendQuery()] --- Request URL = " + urlBuf.toString());
    DefaultHttpClient httpClient=new DefaultHttpClient();
    UsernamePasswordCredentials creds=new UsernamePasswordCredentials(PropertyManager.getPropertyManager().getProperty("nuxeo.auth.login","Administrator"),PropertyManager.getPropertyManager().getProperty("nuxeo.auth.password","Administrator"));
    HttpPost postRequest=new HttpPost(urlBuf.toString());
    postRequest.addHeader(new BasicScheme().authenticate(creds,postRequest));
    HttpEntity entity=new StringEntity(bodyBuf.toString());
    postRequest.setEntity(entity);
    postRequest.addHeader(new BasicHeader("X-NXDocumentProperties","*"));
    postRequest.setHeader(new BasicHeader(HTTP.CONTENT_TYPE,"application/json+nxrequest; charset=UTF-8"));
    HttpResponse response=httpClient.execute(postRequest);
    int status=response.getStatusLine().getStatusCode();
    logger.debug("[sendQuery()] --- sendQuery response status = " + status);
    String textEntity=ContentReader.read(response.getEntity().getContent());
    logger.debug("[sendQuery()] --- sendQuery response = " + textEntity);
    return textEntity;
  }
 catch (  JSONException e) {
    logger.error("Failed to create request body",e);
    return null;
  }
}
 

Example 59

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

Source file: AndroidUrlDownloader.java

  31 
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 60

From project evodroid, under directory /src/com/sonorth/evodroid/.

Source file: AddAccount.java

  31 
vote

private InputStream getResponse(String urlString){
  InputStream in=null;
  URL url=null;
  try {
    url=new URL(urlString);
  }
 catch (  MalformedURLException e1) {
    e1.printStackTrace();
    return null;
  }
  try {
    HttpGet httpRequest=new HttpGet(url.toURI());
    HttpClient httpclient=new DefaultHttpClient();
    HttpResponse response=httpclient.execute(httpRequest);
    HttpEntity entity=response.getEntity();
    BufferedHttpEntity bufHttpEntity=new BufferedHttpEntity(entity);
    in=bufHttpEntity.getContent();
    in.close();
  }
 catch (  ClientProtocolException e) {
    e.printStackTrace();
  }
catch (  URISyntaxException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
catch (  Exception e) {
    e.printStackTrace();
  }
  return in;
}
 

Example 61

From project FlipDroid, under directory /app/src/com/goal98/flipdroid2/model/google/.

Source file: GReader.java

  31 
vote

public void getSidAndAuth(String email,String password) throws HttpException, IOException {
  setEmail(email);
  setPassword(password);
  setAuth_params();
  String sidtag="SID=";
  String authtag="Auth=";
  HttpPost post=new HttpPost(GOOGLE_READER);
  post.setHeader("Content-Type","application/x-www-form-urlencoded");
  HttpEntity entity=new UrlEncodedFormEntity(paramsNameValuePairs,HTTP.UTF_8);
  post.setEntity(entity);
  HttpResponse response=null;
  HttpClient httpclient=new DefaultHttpClient();
  response=httpclient.execute(post);
  int result=response.getStatusLine().getStatusCode();
  if (result == 200) {
    loginstate=200;
    String[] temps=EntityUtils.toString(response.getEntity()).split("\n");
    for (    String temp : temps) {
      if (temp.startsWith(sidtag))       this.sid=temp.substring(sidtag.length());
 else       if (temp.startsWith(authtag))       this.auth=temp.substring(authtag.length());
    }
    isRight();
  }
  post.abort();
  httpclient.getConnectionManager().shutdown();
  httpclient=null;
}
 

Example 62

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

Source file: ClientAbortMethod.java

  31 
vote

public final static void main(String[] args) throws Exception {
  HttpClient httpclient=new DefaultHttpClient();
  try {
    HttpGet httpget=new HttpGet("http://www.apache.org/");
    System.out.println("executing request " + httpget.getURI());
    HttpResponse response=httpclient.execute(httpget);
    HttpEntity entity=response.getEntity();
    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    if (entity != null) {
      System.out.println("Response content length: " + entity.getContentLength());
    }
    System.out.println("----------------------------------------");
    httpget.abort();
  }
  finally {
    httpclient.getConnectionManager().shutdown();
  }
}
 

Example 63

From project Gaggle, under directory /src/com/geeksville/location/.

Source file: LeonardoUpload.java

  31 
vote

/** 
 * Upload a flight to Leonardo
 * @param username
 * @param password
 * @param postURL
 * @param shortFilename
 * @param igcFile we will take care of closing this stram
 * @return null for success, otherwise a string description of the problem
 * @throws IOException
 */
public static String upload(String username,String password,String postURL,int competitionClass,String shortFilename,String igcFile,int connectionTimeout,int operationTimeout) throws IOException {
  int i=shortFilename.lastIndexOf('.');
  if (i >= 1)   shortFilename=shortFilename.substring(0,i);
  String sCompetitionClass=String.valueOf(competitionClass);
  HttpParams httpParameters=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(httpParameters,connectionTimeout);
  HttpConnectionParams.setSoTimeout(httpParameters,operationTimeout);
  HttpClient httpclient=new DefaultHttpClient(httpParameters);
  httpclient.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,false);
  HttpPost httppost=new HttpPost(postURL);
  List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>();
  nameValuePairs.add(new BasicNameValuePair("user",username));
  nameValuePairs.add(new BasicNameValuePair("pass",password));
  nameValuePairs.add(new BasicNameValuePair("igcfn",shortFilename));
  nameValuePairs.add(new BasicNameValuePair("Klasse",sCompetitionClass));
  nameValuePairs.add(new BasicNameValuePair("IGCigcIGC",igcFile));
  httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
  HttpResponse response=httpclient.execute(httppost);
  HttpEntity entity=response.getEntity();
  String resp=EntityUtils.toString(entity);
  if (resp.contains("flight scored"))   resp=null;
 else {
    int bodLoc=resp.indexOf("<body>");
    if (bodLoc >= 0)     resp=resp.substring(bodLoc + 6);
    int probLoc=resp.indexOf("problem");
    if (probLoc >= 0)     resp=resp.substring(probLoc + 7);
    if (resp.startsWith("<br>"))     resp=resp.substring(4);
    int markLoc=resp.indexOf('<');
    if (markLoc >= 0)     resp=resp.substring(0,markLoc);
    resp=resp.trim();
  }
  return resp;
}
 

Example 64

From project Game_3, under directory /android/src/playn/android/.

Source file: AndroidAssets.java

  31 
vote

public Bitmap downloadBitmap(String url){
  final AndroidHttpClient client=AndroidHttpClient.newInstance("Android");
  final HttpGet getRequest=new HttpGet(url);
  try {
    HttpResponse response=client.execute(getRequest);
    final int statusCode=response.getStatusLine().getStatusCode();
    if (statusCode != HttpStatus.SC_OK) {
      Log.w("ImageDownloader","Error " + statusCode + " while retrieving bitmap from "+ url);
      return null;
    }
    final HttpEntity entity=response.getEntity();
    if (entity != null) {
      InputStream inputStream=null;
      try {
        inputStream=entity.getContent();
        return decodeBitmap(inputStream);
      }
  finally {
        if (inputStream != null) {
          inputStream.close();
        }
        entity.consumeContent();
      }
    }
  }
 catch (  Exception e) {
    getRequest.abort();
    Log.w("ImageDownloader","Error while retrieving bitmap from " + url,e);
  }
 finally {
    if (client != null) {
      client.close();
    }
  }
  return null;
}
 

Example 65

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

Source file: SyncService.java

  31 
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 66

From project GeekAlarm, under directory /android/src/com/geek_alarm/android/tasks/.

Source file: TaskManager.java

  31 
vote

public static Task getTask(TaskType taskType) throws Exception {
  String url=String.format("task?type=%s&level=%d",taskType.getType(),taskType.getLevel().getValue());
  HttpEntity taskEntity=sendRequest(url);
  JSONObject taskJson=new JSONObject(EntityUtils.toString(taskEntity));
  String id=taskJson.getString("id");
  Task task=new Task();
  task.setId(id);
  task.setCorrect(Integer.parseInt(taskJson.getString("correct")));
  task.setType(taskType);
  String questionUrl=String.format("image?id=%s&type=question",id);
  task.setQuestion(getImage(questionUrl));
  for (int i=0; i < 4; i++) {
    String choiceUrl=String.format("image?id=%s&type=choice&number=%d",id,i);
    task.setChoice(i,getImage(choiceUrl));
  }
  return task;
}
 

Example 67

From project generic-store-for-android, under directory /src/com/wareninja/opensource/common/.

Source file: CustomBugSenseReportSender.java

  31 
vote

private void submitError(String hash,String data){
  DefaultHttpClient httpClient=new DefaultHttpClient();
  HttpParams params=httpClient.getParams();
  HttpProtocolParams.setUseExpectContinue(params,false);
  HttpConnectionParams.setConnectionTimeout(params,TIMEOUT);
  HttpConnectionParams.setSoTimeout(params,TIMEOUT);
  HttpPost httpPost=new HttpPost(bugSenseEndPoint);
  httpPost.addHeader("X-BugSense-Api-Key",bugSenseApiKey);
  List<NameValuePair> nvps=new ArrayList<NameValuePair>();
  nvps.add(new BasicNameValuePair("data",data));
  nvps.add(new BasicNameValuePair("hash",hash));
  try {
    httpPost.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));
    HttpResponse response=httpClient.execute(httpPost);
    HttpEntity entity=response.getEntity();
    Log.d(TAG,"entity : " + entity);
  }
 catch (  Exception ex) {
    Log.e(TAG,"Error sending exception stacktrace",ex);
  }
}
 

Example 68

From project geolatte-maprenderer, under directory /src/main/java/org/geolatte/maprenderer/sld/graphics/.

Source file: ExternalGraphicsRepository.java

  31 
vote

/** 
 * Retrieves the image from specified URL. If the url points to an SVG, the SVG is rendered at the specified size. If the url points to an bitmap image, then the image is scaled to size only if sizeSet is true.
 * @param url URL to the graphic source.
 * @param size size at which to render the image (for SVG) or to which to scale (if sizeSet)
 * @param sizeSet whether or not a specific size is explicitly requested for the image
 * @return
 * @throws IOException
 */
private BufferedImage retrieve(String url,float size,boolean sizeSet) throws IOException {
  BufferedImage unscaledImage=getFromCache(new ImageKey(url));
  if (unscaledImage != null) {
    return sizeSet ? scale(unscaledImage,size) : unscaledImage;
  }
  SVGDocument cachedSVG=this.svgCache.get(url);
  if (cachedSVG != null) {
    return transCodeSVG(cachedSVG,size);
  }
  HttpEntity entity=retrieveGraphicFromUrl(url);
  if (contentTypeIsSVG(entity)) {
    return SVGFromURLResponse(url,size,entity);
  }
 else {
    return scale(ImageFromURLResponse(url,entity),size);
  }
}
 

Example 69

From project gxa, under directory /annotator/src/main/java/uk/ac/ebi/gxa/annotator/loader/.

Source file: URLContentLoader.java

  31 
vote

public File getContentAsFile(String url,File file) throws AnnotationException {
  HttpGet httpGet=new HttpGet(url);
  final HttpParams params=new BasicHttpParams();
  HttpClientParams.setRedirecting(params,true);
  httpGet.setParams(params);
  FileOutputStream out=null;
  try {
    HttpResponse response=httpClient.execute(httpGet);
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
      throw new AnnotationException("Failed to connect to: " + url + " "+ response.getStatusLine());
    }
    HttpEntity entity=response.getEntity();
    final long responseContentLength=entity.getContentLength();
    out=new FileOutputStream(file);
    entity.writeTo(out);
    out.close();
    final long actualLength=file.length();
    if (actualLength < responseContentLength) {
      log.error("Not all data are loaded actual size {} expected size {}",actualLength,responseContentLength);
      throw new AnnotationException("Failed to download all annotation data from: " + url + " expected size="+ responseContentLength+ " actual="+ actualLength+ ". Please try again!");
    }
  }
 catch (  IOException e) {
    throw new AnnotationException("Fatal transport error when reading from " + url,e);
  }
 finally {
    closeQuietly(out);
  }
  return file;
}
 

Example 70

From project Hawksword, under directory /src/com/bw/hawksword/wiktionary/.

Source file: SimpleWikiHelper.java

  31 
vote

/** 
 * Pull the raw text content of the given URL. This call blocks until the operation has completed, and is synchronized because it uses a shared buffer  {@link #sBuffer}.
 * @param url The exact URL to request.
 * @return The raw content returned by the server.
 * @throws ApiException If any connection or server error occurs.
 */
protected static synchronized String getUrlContent(String url) throws ApiException {
  if (sUserAgent == null) {
    throw new ApiException("User-Agent string must be prepared");
  }
  HttpClient client=new DefaultHttpClient();
  HttpGet request=new HttpGet(url);
  request.setHeader("User-Agent",sUserAgent);
  try {
    HttpResponse response=client.execute(request);
    StatusLine status=response.getStatusLine();
    if (status.getStatusCode() != HTTP_STATUS_OK) {
      throw new ApiException("Invalid response from server: " + status.toString());
    }
    HttpEntity entity=response.getEntity();
    InputStream inputStream=entity.getContent();
    ByteArrayOutputStream content=new ByteArrayOutputStream();
    int readBytes=0;
    while ((readBytes=inputStream.read(sBuffer)) != -1) {
      content.write(sBuffer,0,readBytes);
    }
    return new String(content.toByteArray());
  }
 catch (  IOException e) {
    throw new ApiException("Problem communicating with API",e);
  }
}
 

Example 71

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

Source file: onlineService2Provider.java

  31 
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);
  }
}
 

Example 72

From project android-client, under directory /xwiki-android-rest/src/org/xwiki/android/rest/.

Source file: HttpConnector.java

  29 
vote

private <T extends Resource>T buildResource(Class<T> ofType,HttpEntity from){
  Serializer serializer=new Persister();
  T res=null;
  try {
    res=serializer.read(ofType,EntityUtils.toString(from));
    from.consumeContent();
  }
 catch (  Exception e) {
    Log.e(TAG,e.getMessage());
  }
  return res;
}
 

Example 73

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

Source file: EasSyncService.java

  29 
vote

public EasResponse sendHttpClientPost(String cmd,HttpEntity entity,int timeout) throws IOException {
  HttpClient client=getHttpClient(timeout);
  boolean isPingCommand=cmd.equals(PING_COMMAND);
  String extra=null;
  boolean msg=false;
  if (cmd.startsWith("SmartForward&") || cmd.startsWith("SmartReply&")) {
    int cmdLength=cmd.indexOf('&');
    extra=cmd.substring(cmdLength);
    cmd=cmd.substring(0,cmdLength);
    msg=true;
  }
 else   if (cmd.startsWith("SendMail&")) {
    msg=true;
  }
  String us=makeUriString(cmd,extra);
  HttpPost method=new HttpPost(URI.create(us));
  if (msg && (mProtocolVersionDouble < Eas.SUPPORTED_PROTOCOL_EX2010_DOUBLE)) {
    method.setHeader("Content-Type","message/rfc822");
  }
 else   if (entity != null) {
    method.setHeader("Content-Type","application/vnd.ms-sync.wbxml");
  }
  setHeaders(method,!isPingCommand);
  if (isPingCommand) {
    method.setHeader("Connection","close");
  }
  method.setEntity(entity);
  return executePostWithTimeout(client,method,timeout,isPingCommand);
}
 

Example 74

From project andstatus, under directory /src/org/andstatus/app/net/.

Source file: ConnectionBasicAuth.java

  29 
vote

/** 
 * Retrieve the input stream from the HTTP connection.
 * @param httpEntity
 * @return String
 */
private String retrieveInputStream(HttpEntity httpEntity){
  int length=(int)httpEntity.getContentLength();
  if (length <= 0) {
    length=1024;
  }
  StringBuffer stringBuffer=new StringBuffer(length);
  try {
    InputStreamReader inputStreamReader=new InputStreamReader(httpEntity.getContent(),HTTP.UTF_8);
    char buffer[]=new char[length];
    int count;
    while ((count=inputStreamReader.read(buffer,0,length - 1)) > 0) {
      stringBuffer.append(buffer,0,count);
    }
  }
 catch (  UnsupportedEncodingException e) {
    Log.e(TAG,e.toString());
  }
catch (  IllegalStateException e) {
    Log.e(TAG,e.toString());
  }
catch (  IOException e) {
    Log.e(TAG,e.toString());
  }
  return stringBuffer.toString();
}
 

Example 75

From project andtweet, under directory /src/com/xorcode/andtweet/net/.

Source file: ConnectionBasicAuth.java

  29 
vote

/** 
 * Retrieve the input stream from the HTTP connection.
 * @param httpEntity
 * @return String
 */
private String retrieveInputStream(HttpEntity httpEntity){
  int length=(int)httpEntity.getContentLength();
  StringBuffer stringBuffer=new StringBuffer(length);
  try {
    InputStreamReader inputStreamReader=new InputStreamReader(httpEntity.getContent(),HTTP.UTF_8);
    char buffer[]=new char[length];
    int count;
    while ((count=inputStreamReader.read(buffer,0,length - 1)) > 0) {
      stringBuffer.append(buffer,0,count);
    }
  }
 catch (  UnsupportedEncodingException e) {
    Log.e(TAG,e.toString());
  }
catch (  IllegalStateException e) {
    Log.e(TAG,e.toString());
  }
catch (  IOException e) {
    Log.e(TAG,e.toString());
  }
  return stringBuffer.toString();
}
 

Example 76

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

Source file: Page.java

  29 
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);
}