Java Code Examples for org.apache.http.client.methods.HttpGet

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 AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/util/http/.

Source file: HttpBuilder.java

  18 
vote

private <T>HttpResult<T> doGet(Type target){
  try {
    URI path=createPath(address,query());
    HttpGet get=new HttpGet(path);
    return doRequest(get,target);
  }
 catch (  URISyntaxException e) {
    Log.e(Constants.TAG,"Couldn't create path",e);
    return error();
  }
}
 

Example 2

From project Amantech, under directory /Android/CloudAppStudioAndroid/src/com/cloudappstudio/utility/.

Source file: CloudOAuth.java

  18 
vote

public String getContent(String apiUrl) throws IllegalStateException, IOException {
  DefaultHttpClient httpClient=new DefaultHttpClient();
  BasicHttpParams params=new BasicHttpParams();
  HttpClientParams.setRedirecting(params,false);
  httpClient.setParams(params);
  HttpGet httpget=new HttpGet(apiUrl + "?userInfoOAuth=" + id.getToken());
  HttpResponse response=httpClient.execute(httpget);
  Log.d("debug","" + response.getStatusLine().getStatusCode());
  Log.d("debug","" + response.getStatusLine());
  return this.readTextFromHttpResponse(response);
}
 

Example 3

From project android-rackspacecloud, under directory /main/java/net/elasticgrid/rackspace/cloudservers/.

Source file: XMLCloudServers.java

  18 
vote

public Server getServerDetails(int serverID) throws CloudServersException {
  logger.log(Level.INFO,"Retrieving detailed information for server {0}...",serverID);
  validateServerID(serverID);
  HttpGet request=new HttpGet(getServerManagementURL() + "/servers/" + serverID);
  return buildServer(makeRequestInt(request,net.elasticgrid.rackspace.cloudservers.internal.Server.class));
}
 

Example 4

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

Source file: WebserviceTask.java

  18 
vote

public static HttpResponse makeRequest(String url,List<BasicNameValuePair> params) throws ClientProtocolException, IOException {
  HttpClient client=new DefaultHttpClient();
  String paramString=URLEncodedUtils.format(params,"utf-8");
  Log.d(MSG_TAG,url + "?" + paramString);
  HttpGet request=new HttpGet(url + "?" + paramString);
  return client.execute(request);
}
 

Example 5

From project androidquery, under directory /src/com/androidquery/callback/.

Source file: AbstractAjaxCallback.java

  18 
vote

private void httpGet(String url,Map<String,String> headers,AjaxStatus status) throws IOException {
  AQUtility.debug("get",url);
  url=patchUrl(url);
  HttpGet get=new HttpGet(url);
  httpDo(get,url,headers,status);
}
 

Example 6

From project api-sdk-java, under directory /api-sdk/src/main/java/com/smartling/api/sdk/file/.

Source file: FileApiClientAdapterImpl.java

  18 
vote

public StringResponse getFile(String fileUri,String locale,RetrievalType retrievalType) throws FileApiException {
  String params=buildParamsQuery(new BasicNameValuePair(FILE_URI,fileUri),new BasicNameValuePair(LOCALE,locale),new BasicNameValuePair(RETRIEVAL_TYPE,null == retrievalType ? null : retrievalType.name()));
  HttpGet getRequest=new HttpGet(buildUrl(GET_FILE_API_URL,params));
  StringResponse response=executeHttpcall(getRequest);
  return response;
}
 

Example 7

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

Source file: RemoteWorksheetsHandler.java

  18 
vote

private void considerUpdate(HashMap<String,WorksheetEntry> sheets,String sheetName,Uri targetDir,ContentResolver resolver) throws HandlerException {
  final WorksheetEntry entry=sheets.get(sheetName);
  if (entry == null) {
    Log.w(TAG,"Missing '" + sheetName + "' worksheet data");
    return;
  }
  final long localUpdated=ParserUtils.queryDirUpdated(targetDir,resolver);
  final long serverUpdated=entry.getUpdated();
  Log.d(TAG,"considerUpdate() for " + entry.getTitle() + " found localUpdated="+ localUpdated+ ", server="+ serverUpdated);
  if (localUpdated >= serverUpdated)   return;
  final HttpGet request=new HttpGet(entry.getListFeed());
  final XmlHandler handler=createRemoteHandler(entry);
  mExecutor.execute(request,handler);
}
 

Example 8

From project bbb-java, under directory /src/main/java/org/mconf/bbb/api/.

Source file: JoinServiceBase.java

  18 
vote

protected static String getUrl(HttpClient client,String url) throws IOException, ClientProtocolException {
  HttpGet method=new HttpGet(url);
  HttpResponse httpResponse=client.execute(method);
  if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK)   log.debug("HTTP GET {} return {}",url,httpResponse.getStatusLine().getStatusCode());
  return EntityUtils.toString(httpResponse.getEntity()).trim();
}
 

Example 9

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

Source file: ListReviewsApiHandler.java

  18 
vote

/** 
 * @param page
 * @return
 * @throws ClientProtocolException
 * @throws OAuthMessageSignerException
 * @throws OAuthExpectationFailedException
 * @throws OAuthCommunicationException
 * @throws NotAuthorizedException
 * @throws BookNotFoundException
 * @throws IOException
 * @throws NetworkException 
 */
public Bundle run(int page,int perPage) throws ClientProtocolException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, NotAuthorizedException, BookNotFoundException, IOException, NetworkException {
  long t0=System.currentTimeMillis();
  final String urlBase="http://www.goodreads.com/review/list/%4$s.xml?key=%1$s&v=2&page=%2$s&per_page=%3$s&sort=date_updated&order=d&shelf=all";
  final String url=String.format(urlBase,mManager.getDeveloperKey(),page,perPage,mManager.getUserid());
  HttpGet get=new HttpGet(url);
  XmlResponseParser handler=new XmlResponseParser(mRootFilter);
  mManager.execute(get,handler,true);
  Bundle results=mFilters.getData();
  long t1=System.currentTimeMillis();
  System.out.println("Found " + results.getLong(TOTAL) + " books in "+ (t1 - t0)+ "ms");
  return results;
}
 

Example 10

From project CampusLifePortlets, under directory /src/main/java/org/jasig/portlet/campuslife/dao/.

Source file: ScreenScrapingService.java

  18 
vote

/** 
 * Get HTML content for the specified dining hall.
 * @param diningHall
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
protected String getHtmlContent(String url) throws ClientProtocolException, IOException {
  final DefaultHttpClient httpclient=new DefaultHttpClient();
  final HttpGet httpget=new HttpGet(url);
  final HttpResponse response=httpclient.execute(httpget);
  final InputStream httpStream=response.getEntity().getContent();
  final String content=IOUtils.toString(httpStream);
  return content;
}
 

Example 11

From project chargifyService, under directory /src/main/java/com/mondora/chargify/controller/.

Source file: Chargify.java

  18 
vote

public Customer getCustomerByReference(String reference) throws ChargifyException {
  HttpGet method=new HttpGet("/customers/lookup.xml?reference=" + reference);
  try {
    HttpResponse response=executeHttpMethod(method);
    handleResponseCode(response,method);
    return (Customer)parse(Customer.class,response,method);
  }
 catch (  NotFoundException nfe) {
    return null;
  }
catch (  Exception e) {
    throw new ChargifyException(e);
  }
}
 

Example 12

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

Source file: GSRestClient.java

  18 
vote

/** 
 * Performs a REST GET operation on the given (relative) URL, using the Admin API.
 * @param relativeUrl the Relative URL to the requested object. The rest server IP and port are not required.<p/> example: "processingUnits/Names/default.cassandra" will get the object named "dafault.cassandra" from the list of all processing units.
 * @return An object, the response received from the Admin API.
 * @throws RestException Reporting errors of all types (IO, HTTP, rest etc.)
 */
public final Map<String,Object> getAdminData(final String relativeUrl) throws RestException {
  final String url=getFullUrl("admin/" + relativeUrl);
  logger.finer(MSG_PERFORMING_HTTP_GET + url);
  final HttpGet httpMethod=new HttpGet(url);
  return readHttpAdminMethod(httpMethod);
}
 

Example 13

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

Source file: RemoteWorksheetsHandler.java

  18 
vote

private void considerUpdate(HashMap<String,WorksheetEntry> sheets,String sheetName,Uri targetDir,ContentResolver resolver) throws HandlerException {
  final WorksheetEntry entry=sheets.get(sheetName);
  if (entry == null) {
    Log.w(TAG,"Missing '" + sheetName + "' worksheet data");
    return;
  }
  final long localUpdated=ParserUtils.queryDirUpdated(targetDir,resolver);
  final long serverUpdated=entry.getUpdated();
  Log.d(TAG,"considerUpdate() for " + entry.getTitle() + " found localUpdated="+ localUpdated+ ", server="+ serverUpdated);
  if (localUpdated >= serverUpdated)   return;
  final HttpGet request=new HttpGet(entry.getListFeed());
  final XmlHandler handler=createRemoteHandler(entry);
  mExecutor.execute(request,handler);
}
 

Example 14

From project CyborgFactoids, under directory /src/main/java/com/alta189/cyborg/factoids/util/.

Source file: HTTPUtil.java

  18 
vote

public static String readURL(String url){
  HttpGet request=new HttpGet(url);
  HttpClient httpClient=new DefaultHttpClient();
  try {
    HttpResponse response=httpClient.execute(request);
    return EntityUtils.toString(response.getEntity());
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 15

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

Source file: RemoteWorksheetsHandler.java

  18 
vote

private void considerUpdate(HashMap<String,WorksheetEntry> sheets,String sheetName,Uri targetDir,ContentResolver resolver) throws HandlerException {
  final WorksheetEntry entry=sheets.get(sheetName);
  if (entry == null) {
    Log.w(TAG,"Missing '" + sheetName + "' worksheet data");
    return;
  }
  final long localUpdated=ParserUtils.queryDirUpdated(targetDir,resolver);
  final long serverUpdated=entry.getUpdated();
  Log.d(TAG,"considerUpdate() for " + entry.getTitle() + " found localUpdated="+ localUpdated+ ", server="+ serverUpdated);
  if (localUpdated >= serverUpdated)   return;
  final HttpGet request=new HttpGet(entry.getListFeed());
  final XmlHandler handler=createRemoteHandler(entry);
  mExecutor.execute(request,handler);
}
 

Example 16

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

Source file: RemoteWorksheetsHandler.java

  18 
vote

private void considerUpdate(HashMap<String,WorksheetEntry> sheets,String sheetName,Uri targetDir,ContentResolver resolver) throws HandlerException {
  final WorksheetEntry entry=sheets.get(sheetName);
  if (entry == null) {
    Log.w(TAG,"Missing '" + sheetName + "' worksheet data");
    return;
  }
  final long localUpdated=ParserUtils.queryDirUpdated(targetDir,resolver);
  final long serverUpdated=entry.getUpdated();
  Log.d(TAG,"considerUpdate() for " + entry.getTitle() + " found localUpdated="+ localUpdated+ ", server="+ serverUpdated);
  if (localUpdated >= serverUpdated)   return;
  final HttpGet request=new HttpGet(entry.getListFeed());
  final XmlHandler handler=createRemoteHandler(entry);
  mExecutor.execute(request,handler);
}
 

Example 17

From project Absolute-Android-RSS, under directory /src/com/AA/Other/.

Source file: RSSParse.java

  17 
vote

/** 
 * Get the XML document for the RSS feed
 * @return the XML Document for the feed on success, on error returns null
 */
private static Document getDocument(){
  Document doc=null;
  try {
    DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
    DefaultHttpClient client=new DefaultHttpClient();
    HttpGet request=new HttpGet(URI);
    HttpResponse response=client.execute(request);
    doc=builder.parse(response.getEntity().getContent());
  }
 catch (  java.io.IOException e) {
    return null;
  }
catch (  SAXException e) {
    Log.e("AARSS","Parse Exception in RSS feed",e);
    return null;
  }
catch (  Exception e) {
    return null;
  }
  return doc;
}
 

Example 18

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

Source file: SGS.java

  17 
vote

@Override public RequestStatus checkRequestStatus(Request request) throws Exception {
  if (!loggedIn) {
    login();
  }
  HttpGet get;
  HttpResponse response;
  TagNode document, statusCell;
  String statusLabel;
  try {
    if (request.getRemoteIdentifier() == null || request.getRemoteIdentifier().length() == 0) {
      throw new RobotException("Invalid remote identifier");
    }
    get=new HttpGet(baseUrl + requestViewAction + "&folio="+ request.getRemoteIdentifier());
    get.addHeader("Referer",baseUrl + requestListAction);
    response=client.execute(get);
    document=cleaner.clean(new InputStreamReader(response.getEntity().getContent(),characterEncoding));
    statusCell=document.findElementByAttValue("width","36%",true,true);
    if (statusCell == null) {
      throw new RobotException("Invalid status text cell");
    }
    statusLabel=statusCell.getText().toString().trim();
    if (statusLabel.equals("En Proceso")) {
      return RequestStatus.PENDING;
    }
 else     if (statusLabel.equals("Respondida")) {
      return RequestStatus.RESPONDED;
    }
 else {
      return null;
    }
  }
 catch (  Exception ex) {
    logger.error(ex.getMessage(),ex);
    throw ex;
  }
}
 

Example 19

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

Source file: YahooQuoteService.java

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

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

Source file: DownloadServiceImpl.java

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

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

Source file: Http.java

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

From project android-api_1, under directory /android-lib/src/com/catchnotes/api/.

Source file: CatchAPI.java

  17 
vote

private HttpResponse performGET(String method,List<NameValuePair> httpParams,boolean useToken){
  HttpGet httpget;
  String uri=method;
  if (!uri.startsWith("http")) {
    uri=catchBaseUrl + uri;
  }
  if (httpParams == null || httpParams.isEmpty()) {
    httpget=new HttpGet(uri);
  }
 else {
    httpget=new HttpGet(uri + '?' + URLEncodedUtils.format(httpParams,"UTF-8"));
  }
  HttpResponse response=null;
  try {
    response=useToken ? getHttpClient().execute(httpget) : getHttpClientNoToken().execute(httpget);
  }
 catch (  ClientProtocolException e) {
    log("caught ClientProtocolException performing GET " + httpget.getURI(),e);
    return null;
  }
catch (  UnknownHostException e) {
    log("caught UnknownHostException performing GET " + httpget.getURI(),null);
    return null;
  }
catch (  IOException e) {
    log("caught IOException performing GET " + httpget.getURI(),e);
    return null;
  }
  sync_trace("GET " + httpget.getURI() + " returned "+ response.getStatusLine().getStatusCode()+ ' '+ response.getStatusLine().getReasonPhrase());
  return response;
}
 

Example 23

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

Source file: Chalmrest.java

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

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

Source file: HttpConnector.java

  17 
vote

/** 
 * Perform HTTP Get method execution and return the response as a String
 * @param Uri URL of XWiki RESTful API
 * @return Response data of the HTTP connection as a String
 */
public String getResponse(String Uri) throws RestConnectionException, RestException {
  initialize();
  BufferedReader in=null;
  HttpGet request=new HttpGet();
  String responseText=new String();
  try {
    requestUri=new URI(Uri);
  }
 catch (  URISyntaxException e) {
    e.printStackTrace();
  }
  setCredentials();
  request.setURI(requestUri);
  Log.d("GET Request URL",Uri);
  try {
    response=client.execute(request);
    Log.d("Response status",response.getStatusLine().toString());
    in=new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuffer sb=new StringBuffer("");
    String line="";
    String NL=System.getProperty("line.separator");
    while ((line=in.readLine()) != null) {
      sb.append(line + NL);
    }
    in.close();
    responseText=sb.toString();
    Log.d("Response","response: " + responseText);
    validate(response.getStatusLine().getStatusCode());
  }
 catch (  ClientProtocolException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
    throw new RestConnectionException(e);
  }
  return responseText;
}
 

Example 25

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

Source file: RSSReader.java

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

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

Source file: WebClient.java

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

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

Source file: BooksStore.java

  17 
vote

/** 
 * Finds the book with the specified id.
 * @param id The id of the book to find (ISBN-10, ISBN-13, etc.)
 * @return A Book instance if the book was found or null otherwise.
 */
public Book findBook(String id){
  final Uri.Builder uri=buildFindBookQuery(id);
  final HttpGet get=new HttpGet(uri.build().toString());
  final Book book=createBook();
  final boolean[] result=new boolean[1];
  try {
    executeRequest(new HttpHost(mHost,80,"http"),get,new ResponseHandler(){
      public void handleResponse(      InputStream in) throws IOException {
        parseResponse(in,new ResponseParser(){
          public void parseResponse(          XmlPullParser parser) throws XmlPullParserException, IOException {
            result[0]=parseBook(parser,book);
          }
        }
);
      }
    }
);
    if (TextUtils.isEmpty(book.mEan) && id.length() == 13) {
      book.mEan=id;
    }
 else     if (TextUtils.isEmpty(book.mIsbn) && id.length() == 10) {
      book.mIsbn=id;
    }
    return result[0] ? book : null;
  }
 catch (  IOException e) {
    android.util.Log.e(LOG_TAG,"Could not find the item with ISBN/EAN: " + id);
  }
  return null;
}
 

Example 28

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

Source file: JsonRequest.java

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

From project android_aosp_packages_apps_Settings, under directory /src/com/android/settings/.

Source file: RadioInfo.java

  17 
vote

/** 
 * This function checks for basic functionality of HTTP Client.
 */
private void httpClientTest(){
  HttpClient client=new DefaultHttpClient();
  try {
    HttpGet request=new HttpGet("http://www.google.com");
    HttpResponse response=client.execute(request);
    if (response.getStatusLine().getStatusCode() == 200) {
      mHttpClientTestResult="Pass";
    }
 else {
      mHttpClientTestResult="Fail: Code: " + String.valueOf(response);
    }
    request.abort();
  }
 catch (  IOException e) {
    mHttpClientTestResult="Fail: IOException";
  }
}
 

Example 30

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

Source file: ConnectionBasicAuth.java

  17 
vote

/** 
 * Execute a GET request against the Twitter REST API.
 * @param url
 * @param client
 * @return String
 * @throws ConnectionException
 */
private String getRequest(String url,HttpClient client) throws ConnectionException {
  String result=null;
  int statusCode=0;
  HttpGet getMethod=new HttpGet(url);
  try {
    getMethod.setHeader("User-Agent",USER_AGENT);
    getMethod.addHeader("Authorization","Basic " + getCredentials());
    client.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT,DEFAULT_GET_REQUEST_TIMEOUT);
    client.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT,DEFAULT_GET_REQUEST_TIMEOUT);
    HttpResponse httpResponse=client.execute(getMethod);
    statusCode=httpResponse.getStatusLine().getStatusCode();
    result=retrieveInputStream(httpResponse.getEntity());
  }
 catch (  Exception e) {
    Log.e(TAG,"getRequest: " + e.toString());
    throw new ConnectionException(e);
  }
 finally {
    getMethod.abort();
  }
  parseStatusCode(statusCode,url);
  return result;
}
 

Example 31

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

Source file: ConnectionBasicAuth.java

  17 
vote

/** 
 * Execute a GET request against the Twitter REST API.
 * @param url
 * @param client
 * @return String
 * @throws ConnectionException
 */
private String getRequest(String url,HttpClient client) throws ConnectionException {
  String result=null;
  int statusCode=0;
  HttpGet getMethod=new HttpGet(url);
  try {
    getMethod.setHeader("User-Agent",USER_AGENT);
    getMethod.addHeader("Authorization","Basic " + getCredentials());
    client.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT,DEFAULT_GET_REQUEST_TIMEOUT);
    client.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT,DEFAULT_GET_REQUEST_TIMEOUT);
    HttpResponse httpResponse=client.execute(getMethod);
    statusCode=httpResponse.getStatusLine().getStatusCode();
    result=retrieveInputStream(httpResponse.getEntity());
  }
 catch (  Exception e) {
    Log.e(TAG,"getRequest: " + e.toString());
    throw new ConnectionException(e);
  }
 finally {
    getMethod.abort();
  }
  parseStatusCode(statusCode,url);
  return result;
}
 

Example 32

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

Source file: AnkiDroidProxy.java

  17 
vote

/** 
 * Get shared decks.
 */
public static List<SharedDeck> getSharedDecks() throws Exception {
  try {
    if (sSharedDecks == null) {
      sSharedDecks=new ArrayList<SharedDeck>();
      HttpGet httpGet=new HttpGet(SYNC_SEARCH);
      httpGet.setHeader("Accept-Encoding","identity");
      httpGet.setHeader("Host",SYNC_HOST);
      DefaultHttpClient defaultHttpClient=new DefaultHttpClient();
      HttpResponse httpResponse=defaultHttpClient.execute(httpGet);
      String response=Utils.convertStreamToString(httpResponse.getEntity().getContent());
      sSharedDecks.addAll(getSharedDecksListFromJSONArray(new JSONArray(response)));
    }
  }
 catch (  Exception e) {
    sSharedDecks=null;
    throw new Exception();
  }
  return sSharedDecks;
}
 

Example 33

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

Source file: ModuleUtils.java

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

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

Source file: ImageManager.java

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

From project b3log-latke, under directory /latke-client/src/main/java/org/b3log/latke/client/.

Source file: LatkeClient.java

  17 
vote

/** 
 * Gets repository names.
 * @return repository names
 * @throws Exception exception
 */
private static Set<String> getRepositoryNames() throws Exception {
  final HttpClient httpClient=new DefaultHttpClient();
  final List<NameValuePair> qparams=new ArrayList<NameValuePair>();
  qparams.add(new BasicNameValuePair("userName",userName));
  qparams.add(new BasicNameValuePair("password",password));
  final URI uri=URIUtils.createURI("http",serverAddress,-1,GET_REPOSITORY_NAMES,URLEncodedUtils.format(qparams,"UTF-8"),null);
  final HttpGet request=new HttpGet();
  request.setURI(uri);
  if (verbose) {
    System.out.println("Getting repository names[" + GET_REPOSITORY_NAMES + "]");
  }
  final HttpResponse httpResponse=httpClient.execute(request);
  final InputStream contentStream=httpResponse.getEntity().getContent();
  final String content=IOUtils.toString(contentStream).trim();
  if (verbose) {
    printResponse(content);
  }
  final JSONObject result=new JSONObject(content);
  final JSONArray repositoryNames=result.getJSONArray("repositoryNames");
  final Set<String> ret=new HashSet<String>();
  for (int i=0; i < repositoryNames.length(); i++) {
    final String repositoryName=repositoryNames.getString(i);
    ret.add(repositoryName);
    final File dir=new File(backupDir.getPath() + File.separatorChar + repositoryName);
    if (!dir.exists() && verbose) {
      dir.mkdir();
      System.out.println("Created a directory[name=" + dir.getName() + "] under backup directory[path="+ backupDir.getPath()+ "]");
    }
  }
  return ret;
}
 

Example 36

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

Source file: RSSReader.java

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

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

Source file: LoaderImageView.java

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

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

Source file: RequestHandler.java

  17 
vote

public String get(String link,int extraHeaders) throws RequestHandlerException {
  if ("".equals(link)) {
    throw new RequestHandlerException("No link found.");
  }
  try {
    HttpGet httpGet=new HttpGet(link.replace(" ","%20"));
    httpGet.setHeaders(HttpHeaders.GET_HEADERS.get(extraHeaders));
    httpGet.setHeader("Referer",link);
    HttpResponse httpResponse=RequestHandler.httpClient.execute(httpGet);
    HttpEntity httpEntity=httpResponse.getEntity();
    if (httpEntity != null) {
      return EntityUtils.toString(httpEntity);
    }
  }
 catch (  ClientProtocolException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
catch (  Exception ex) {
    throw new RequestHandlerException(ex.getMessage());
  }
  return "";
}
 

Example 39

From project bitfluids, under directory /src/main/java/at/bitcoin_austria/bitfluids/.

Source file: PriceService.java

  17 
vote

public synchronized Double getEurQuote() throws RemoteSystemFail {
  if ((lastResult != null) && (new Date().getTime() - lastTimeChecked < Utils.TEN_MINUTES_IN_MILLIS)) {
    notifySuccess();
    return lastResult;
  }
  HttpResponse httpResponse;
  HttpGet httpGet=new HttpGet(Utils.MTGOX_BTCEUR);
  try {
    httpResponse=httpClient.execute(httpGet);
    StatusLine statusLine=httpResponse.getStatusLine();
    if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
      ByteArrayOutputStream out=new ByteArrayOutputStream();
      httpResponse.getEntity().writeTo(out);
      out.close();
      JSONObject json=new JSONObject(out.toString());
      String btc_eur=((JSONObject)((JSONObject)json.get("return")).get("avg")).get("value").toString();
      lastResult=Double.parseDouble(btc_eur);
      lastTimeChecked=new Date().getTime();
      notifySuccess();
      return lastResult;
    }
 else {
      httpResponse.getEntity().getContent().close();
      throw new RemoteSystemFail("ERROR: " + statusLine.getReasonPhrase());
    }
  }
 catch (  ClientProtocolException e) {
    notifyFailed();
    throw new RemoteSystemFail(e);
  }
catch (  IOException e) {
    notifyFailed();
    throw new RemoteSystemFail(e);
  }
catch (  JSONException e) {
    notifyFailed();
    throw new RemoteSystemFail(e);
  }
}
 

Example 40

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

Source file: ArtifactoryBuildInfoClient.java

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

From project callmeter, under directory /src/de/ub0r/android/callmeter/ui/prefs/.

Source file: Preferences.java

  17 
vote

/** 
 * Get a  {@link InputStream} from {@link Uri}.
 * @param cr {@link ContentResolver}
 * @param uri {@link Uri}
 * @return {@link InputStream}
 */
private InputStream getStream(final ContentResolver cr,final Uri uri){
  if (uri.toString().equals("content://default")) {
    return IS_DEFAULT;
  }
 else   if (uri.toString().startsWith("import")) {
    String url;
    if (uri.getScheme().equals("imports")) {
      url="https:/";
    }
 else {
      url="http:/";
    }
    url+=uri.getPath();
    final HttpGet request=new HttpGet(url);
    Log.d(TAG,"url: " + url);
    try {
      final HttpResponse response=new DefaultHttpClient().execute(request);
      int resp=response.getStatusLine().getStatusCode();
      if (resp != HttpStatus.SC_OK) {
        return null;
      }
      return response.getEntity().getContent();
    }
 catch (    IOException e) {
      Log.e(TAG,"error in reading export: " + url,e);
      return null;
    }
  }
 else   if (uri.toString().startsWith("content://") || uri.toString().startsWith("file://")) {
    try {
      return cr.openInputStream(uri);
    }
 catch (    IOException e) {
      Log.e(TAG,"error in reading export: " + uri.toString(),e);
      return null;
    }
  }
  Log.d(TAG,"getStream() returns null, " + uri.toString());
  return null;
}
 

Example 42

From project CheckIn4Me, under directory /src/com/davidivins/checkin4me/oauth/.

Source file: OAuth2Request.java

  17 
vote

/** 
 * execute
 * @return Response from executing the request
 */
@Override public Response execute(){
  BufferedReader page=null;
  OAuthResponse response=new OAuthResponse();
  Log.i(TAG,"executing OAuth 2.0 request...");
  String url_string=generateURL();
  Log.i(TAG,"request url = " + url_string);
  try {
    HttpClient httpclient=getTolerantClient();
    HttpResponse http_response;
    if (method.equals("GET")) {
      HttpGet httpget=new HttpGet(url_string);
      http_response=httpclient.execute(httpget);
    }
 else {
      HttpPost httppost=new HttpPost(url_string);
      http_response=httpclient.execute(httppost);
    }
    page=new BufferedReader(new InputStreamReader(http_response.getEntity().getContent(),RESPONSE_ENCODING));
    String line;
    while ((line=page.readLine()) != null) {
      Log.i(TAG,"line = " + line);
      response.appendResponseString(line);
    }
    response.setSuccessStatus(true);
  }
 catch (  IOException e) {
    response.set(false,e.getMessage());
    Log.e(TAG,"EXCEPTION: " + e.getMessage());
  }
  Log.i(TAG,"response.getSuccessStatus = " + response.getSuccessStatus());
  Log.i(TAG,"response.getResponseString = " + response.getResponseString());
  return response;
}
 

Example 43

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

Source file: ActualInfo.java

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

From project CineShowTime-Android, under directory /Libraries/CineShowTime/src/com/binomed/showtime/android/util/.

Source file: CineShowtimeFactory.java

  17 
vote

private HttpGet getGetMethod(){
  if (getMethod == null) {
    getMethod=new HttpGet();
  }
  return getMethod;
}
 

Example 45

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

Source file: RESTHelper.java

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

From project Cloud-Shout, under directory /ckdgcloudshout-AppEngine/src/com/appspot/ckdgcloudshout/.

Source file: DownloadTest.java

  17 
vote

public static void main(String[] args){
  try {
    HttpResponse response=new DefaultHttpClient().execute(new HttpGet("http://localhost:8888/downloadmedia"));
    response.getStatusLine().getStatusCode();
    response.getAllHeaders();
  }
 catch (  ClientProtocolException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 47

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

Source file: InternalResponseTest.java

  17 
vote

@Test public void testCaseInsensitiveHeaders(){
  HttpRequestBase req=new HttpGet();
  HttpResponse response=new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP",1,1),200,"OK"));
  response.setHeaders(new Header[]{new BasicHeader("namE1","val1"),new BasicHeader("Name1","val2"),new BasicHeader("NAME1","val3")});
  HttpClientResponse clientResponse=new InternalResponse(req,response);
  Map<String,List<String>> expectedAllHeaders=Maps.newHashMap();
  List<String> values=Lists.newArrayList("val1","val2","val3");
  expectedAllHeaders.put("namE1",values);
  assertEquals(values,clientResponse.getHeaders("name1"));
  assertEquals(values,clientResponse.getHeaders("naMe1"));
  assertEquals(expectedAllHeaders,clientResponse.getAllHeaders());
}
 

Example 48

From project Core_2, under directory /shell/src/main/java/org/jboss/forge/shell/util/.

Source file: PluginUtil.java

  17 
vote

public static List<PluginRef> findPlugin(final Shell shell,Configuration config,final String searchString,boolean speak) throws Exception {
  String defaultRepo=getDefaultRepo(shell.getEnvironment());
  InputStream repoStream=getCachedRepoStream(getDefaultRepo(shell.getEnvironment()),shell.getEnvironment());
  if (repoStream == null) {
    HttpGet httpGet=new HttpGet(defaultRepo);
    if (speak)     shell.print("Connecting to remote repository [" + defaultRepo + "]... ");
    DefaultHttpClient client=new DefaultHttpClient();
    configureProxy(ProxySettings.fromForgeConfiguration(config),client);
    HttpResponse httpResponse=client.execute(httpGet);
switch (httpResponse.getStatusLine().getStatusCode()) {
case 200:
      if (speak)       shell.println("connected!");
    break;
case 404:
  if (speak)   shell.println("failed! (plugin index not found: " + defaultRepo + ")");
return Collections.emptyList();
default :
if (speak) shell.println("failed! (server returned status code: " + httpResponse.getStatusLine().getStatusCode());
return Collections.emptyList();
}
repoStream=httpResponse.getEntity().getContent();
setCachedRepoStream(defaultRepo,shell.getEnvironment(),repoStream);
repoStream=getCachedRepoStream(getDefaultRepo(shell.getEnvironment()),shell.getEnvironment());
}
return getPluginsFromRepoStream(searchString,repoStream);
}
 

Example 49

From project creamed_glacier_app_settings, under directory /src/com/android/settings/.

Source file: RadioInfo.java

  17 
vote

/** 
 * This function checks for basic functionality of HTTP Client.
 */
private void httpClientTest(){
  HttpClient client=new DefaultHttpClient();
  try {
    HttpGet request=new HttpGet("http://www.google.com");
    HttpResponse response=client.execute(request);
    if (response.getStatusLine().getStatusCode() == 200) {
      mHttpClientTestResult="Pass";
    }
 else {
      mHttpClientTestResult="Fail: Code: " + String.valueOf(response);
    }
    request.abort();
  }
 catch (  IOException e) {
    mHttpClientTestResult="Fail: IOException";
  }
}
 

Example 50

From project cw-advandroid, under directory /Honeycomb/WeatherFragment/src/com/commonsware/android/weather/.

Source file: WeatherBinder.java

  17 
vote

@Override protected ArrayList<Forecast> doInBackground(Location... locs){
  DefaultHttpClient client=new DefaultHttpClient();
  ArrayList<Forecast> result=null;
  try {
    Location loc=locs[0];
    String url=String.format(format,loc.getLatitude(),loc.getLongitude());
    HttpGet getMethod=new HttpGet(url);
    ResponseHandler<String> responseHandler=new BasicResponseHandler();
    String responseBody=client.execute(getMethod,responseHandler);
    result=buildForecasts(responseBody);
  }
 catch (  Exception e) {
    this.e=e;
  }
  client.getConnectionManager().shutdown();
  return (result);
}
 

Example 51

From project cw-android, under directory /Internet/Weather/src/com/commonsware/android/internet/.

Source file: WeatherDemo.java

  17 
vote

private void updateForecast(Location loc){
  String url=String.format(format,loc.getLatitude(),loc.getLongitude());
  HttpGet getMethod=new HttpGet(url);
  try {
    ResponseHandler<String> responseHandler=new BasicResponseHandler();
    String responseBody=client.execute(getMethod,responseHandler);
    buildForecasts(responseBody);
    String page=generatePage();
    browser.loadDataWithBaseURL(null,page,"text/html","UTF-8",null);
  }
 catch (  Throwable t) {
    android.util.Log.e("WeatherDemo","Exception fetching data",t);
    Toast.makeText(this,"Request failed: " + t.toString(),Toast.LENGTH_LONG).show();
  }
}
 

Example 52

From project cw-omnibus, under directory /MAT/RandomAppOfCrap/src/com/commonsware/android/weather/.

Source file: WeatherBinder.java

  17 
vote

@Override protected ArrayList<Forecast> doInBackground(Location... locs){
  ArrayList<Forecast> result=null;
  try {
    Location loc=locs[0];
    String url=String.format(urlTemplate,loc.getLatitude(),loc.getLongitude());
    HttpGet getMethod=new HttpGet(url);
    ResponseHandler<String> responseHandler=new BasicResponseHandler();
    String responseBody=client.execute(getMethod,responseHandler);
    result=buildForecasts(responseBody);
    client.getConnectionManager().shutdown();
  }
 catch (  Exception e) {
    this.e=e;
  }
  return (result);
}
 

Example 53

From project DeliciousDroid, under directory /src/com/deliciousdroid/client/.

Source file: DeliciousFeed.java

  17 
vote

/** 
 * Retrieves a list of contacts in a users network.
 * @param account The account being synced.
 * @return The list of contacts received from the server.
 * @throws JSONException If an error was encountered in deserializing the JSON object returned from the server.
 * @throws IOException If a server error was encountered.
 * @throws AuthenticationException If an authentication error was encountered.
 */
public static List<User> fetchFriendUpdates(Account account) throws JSONException, IOException, AuthenticationException, FeedForbiddenException {
  final ArrayList<User> friendList=new ArrayList<User>();
  final HttpGet post=new HttpGet(FETCH_FRIEND_UPDATES_URI + account.name);
  final HttpResponse resp=HttpClientFactory.getThreadSafeClient().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     if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
      Log.e(TAG,"Fetching contact updates forbidden");
      throw new FeedForbiddenException();
    }
 else {
      Log.e(TAG,"Server error in fetching remote contacts: " + resp.getStatusLine());
      throw new IOException();
    }
  }
  return friendList;
}
 

Example 54

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

Source file: MainActivity.java

  17 
vote

void startBuy(){
  ClockworkModBillingClient.getInstance().refreshMarketPurchases();
  final ProgressDialog dlg=new ProgressDialog(MainActivity.this);
  dlg.setMessage(getString(R.string.retrieving_status));
  dlg.show();
  ThreadingRunnable.background(new ThreadingRunnable(){
    @Override public void run(){
      try {
        final HttpGet get=new HttpGet(ServiceHelper.STATUS_URL);
        final JSONObject payload=ServiceHelper.retryExecuteAsJSONObject(MainActivity.this,mSettings.getString("account"),new URL(ServiceHelper.STATUS_URL),null);
        final long expiration=payload.getLong("subscription_expiration");
        foreground(new Runnable(){
          @Override public void run(){
            refreshAccount(expiration);
            dlg.dismiss();
            Intent i=new Intent(MainActivity.this,BuyActivity.class);
            i.putExtra("payload",payload.toString());
            startActivityForResult(i,2323);
          }
        }
);
      }
 catch (      Exception ex) {
        foreground(new Runnable(){
          @Override public void run(){
            dlg.dismiss();
            Helper.showAlertDialog(MainActivity.this,R.string.status_error);
          }
        }
);
        ex.printStackTrace();
      }
    }
  }
);
}
 

Example 55

From project DigitbooksExamples, under directory /DigitbooksExamples/src/fr/digitbooks/android/examples/chapitre08/.

Source file: DigibooksRatingApi.java

  17 
vote

public static String requestRatings(int count,String format){
  String response=null;
  StringBuffer stringBuffer=new StringBuffer();
  BufferedReader bufferedReader=null;
  try {
    HttpGet httpGet=new HttpGet();
    URI uri=new URI(Config.URL_SERVER + "data?count=" + count+ "&format="+ format);
    httpGet.setURI(uri);
    AndroidHttpClient httpClient=AndroidHttpClient.newInstance("");
    HttpResponse httpResponse=httpClient.execute(httpGet);
    InputStream inputStream=httpResponse.getEntity().getContent();
    bufferedReader=new BufferedReader(new InputStreamReader(inputStream),1024);
    String readLine=bufferedReader.readLine();
    while (readLine != null) {
      stringBuffer.append(readLine);
      readLine=bufferedReader.readLine();
    }
    httpClient.close();
  }
 catch (  Exception e) {
    Log.e(LOG_TAG,"IOException trying to execute request for " + e);
    return null;
  }
 finally {
    if (bufferedReader != null) {
      try {
        bufferedReader.close();
      }
 catch (      IOException e) {
        return null;
      }
    }
    response=stringBuffer.toString();
    if (Config.INFO_LOGS_ENABLED) {
      Log.i(LOG_TAG,"Reponse = " + response);
    }
  }
  return response;
}
 

Example 56

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 get(DirectMemoryRequest request) throws DirectMemoryException {
  String uri=buildRequestWithKey(request);
  log.debug("get request to: {}",uri);
  HttpGet httpGet=new HttpGet(uri);
  httpGet.addHeader("Accept",getAcceptContentType(request));
  if (request.getExchangeType() == ExchangeType.TEXT_PLAIN) {
    httpGet.addHeader(DirectMemoryHttpConstants.SERIALIZER_HTTP_HEADER,request.getSerializer().getClass().getName());
  }
  try {
    HttpResponse httpResponse=this.httpClient.execute(httpGet);
    StatusLine statusLine=httpResponse.getStatusLine();
    if (statusLine.getStatusCode() == 204) {
      return new DirectMemoryResponse().setFound(false);
    }
    if (request.isDeleteRequest()) {
      return new DirectMemoryResponse().setFound(true).setDeleted(true);
    }
    return buildResponse(httpResponse.getEntity().getContent(),request).setFound(true);
  }
 catch (  IOException e) {
    throw new DirectMemoryException(e.getMessage(),e);
  }
}
 

Example 57

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

Source file: NetworkHelper.java

  17 
vote

public String doHTTPGet(String uri){
  Log.d("Discogs","Requesting:" + uri);
  String response=null;
  HttpGet hTTPGet=new HttpGet(uri);
  try {
    consumer.sign(hTTPGet);
    HttpResponse hTTPResponse=httpClient.execute(hTTPGet);
    response=EntityUtils.toString(hTTPResponse.getEntity());
    Log.d("Discogs","Response: " + response);
  }
 catch (  MalformedURLException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
catch (  OAuthMessageSignerException e) {
    e.printStackTrace();
  }
catch (  OAuthExpectationFailedException e) {
    e.printStackTrace();
  }
catch (  OAuthCommunicationException e) {
    e.printStackTrace();
  }
  return response;
}
 

Example 58

From project DrmLicenseService, under directory /src/com/sonyericsson/android/drm/drmlicenseservice/.

Source file: HttpClient.java

  17 
vote

public static Response get(Context context,long sessionId,String url,Bundle parameters,DataHandlerCallback callback,RetryCallback retryCallback){
  Response response=null;
  final String fUrl=url;
  final Bundle fParameters=parameters;
  response=runAsThread(context,sessionId,parameters,retryCallback,new HttpThread.HttpThreadAction(callback){
    public HttpRequestBase getRequest(){
      HttpGet request=null;
      if (fUrl != null && fUrl.length() > 0) {
        try {
          request=new HttpGet(fUrl);
        }
 catch (        IllegalArgumentException e) {
          return null;
        }
        addParameters(fParameters,request);
      }
      return request;
    }
  }
);
  return response;
}
 

Example 59

From project droidkit, under directory /src/org/droidkit/app/.

Source file: UpdateService.java

  17 
vote

private void queryServer(){
  DefaultHttpClient client=new DefaultHttpClient();
  HttpGet get=new HttpGet(mUpdateServer + "?foobar=boo");
  StringBuffer obj=new StringBuffer();
  Log.i("DroidKit","Checking updates: " + mUpdateServer);
  try {
    HttpResponse response=client.execute(get);
    InputStream in=response.getEntity().getContent();
    BufferedReader reader=new BufferedReader(new InputStreamReader(in),(int)response.getEntity().getContentLength());
    String line="";
    while ((line=reader.readLine()) != null) {
      obj.append(line);
      obj.append("\n");
    }
  }
 catch (  ClientProtocolException e) {
    Log.e("DroidKit","Error contacting update server: " + e.toString());
  }
catch (  IOException e) {
    Log.e("DroidKit","Error contacting update server: " + e.toString());
  }
  client.getConnectionManager().shutdown();
  parseJSONResponse(obj.toString());
}
 

Example 60

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

Source file: RESTClient.java

  17 
vote

public String get(String uri) throws HTTPException {
  L.d("GET on " + uri);
  String respStr;
  if (useHttpURLConnection()) {
    HttpURLConnectionWrapper wrapper=getModern();
    HttpURLConnection conn=wrapper.getConnectedHttpURLConnection(uri,GET);
    respStr=HttpURLConnectionWrapper.getResponseBodyAndDisconnect(conn);
  }
 else {
    DefaultHttpClientWrapper wrapper=getLegacy();
    HttpGet req=new HttpGet(uri);
    HttpResponse resp=wrapper.getResponse(req);
    respStr=DefaultHttpClientWrapper.getResponseBody(resp);
    DefaultHttpClientWrapper.consumeResponse(resp);
  }
  return respStr;
}
 

Example 61

From project dungbeetle, under directory /src/edu/stanford/mobisocial/dungbeetle/google/.

Source file: OAuthFlowApp.java

  17 
vote

private String doGet(String url,OAuthConsumer consumer) throws Exception {
  DefaultHttpClient httpclient=new DefaultHttpClient();
  HttpGet request=new HttpGet(url);
  Log.i(TAG,"Requesting URL : " + url);
  consumer.sign(request);
  HttpResponse response=httpclient.execute(request);
  Log.i(TAG,"Statusline : " + response.getStatusLine());
  InputStream data=response.getEntity().getContent();
  BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(data));
  String responeLine;
  StringBuilder responseBuilder=new StringBuilder();
  while ((responeLine=bufferedReader.readLine()) != null) {
    responseBuilder.append(responeLine);
  }
  Log.i(TAG,"Response : " + responseBuilder.toString());
  return responseBuilder.toString();
}
 

Example 62

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

Source file: ReadDataAsyncTask.java

  17 
vote

@Override protected Boolean doInBackground(String... params){
  try {
    HttpClient httpClient=new DefaultHttpClient();
    HttpParams httpParams=httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams,30000);
    HttpConnectionParams.setSoTimeout(httpParams,30000);
    HttpGet get=new HttpGet(params[0]);
    mData=httpClient.execute(get,new BasicResponseHandler());
    return true;
  }
 catch (  ClientProtocolException ex) {
    mErrorMessage=ex.getMessage();
  }
catch (  IOException ex) {
    mErrorMessage=ex.getMessage();
  }
  return false;
}
 

Example 63

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

Source file: SoapMessageHandler.java

  17 
vote

/** 
 * Check if a WSDL service exists
 * @param url The url to check
 * @return true if the WSDL service send a response, false otherwise.
 */
private boolean checkWsdl(String url){
  boolean result=false;
  logger.debug("Checking wsdl for url : " + url + "?wsdl");
  try {
    DefaultHttpClient httpClient=new DefaultHttpClient();
    HttpGet httpGet=new HttpGet(url + "?wsdl");
    httpClient.execute(httpGet);
    logger.debug("WSDL found !");
    result=true;
  }
 catch (  Exception ex) {
    logger.debug("Unable to get a correct response from " + url + "?wsdl");
  }
  return result;
}
 

Example 64

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

Source file: HttpClient4.java

  16 
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 65

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

Source file: HttpClient4.java

  16 
vote

public HttpResponseMessage execute(HttpMessage request) throws IOException {
  final String method=request.method;
  final String url=request.url.toExternalForm();
  final InputStream body=request.getBody();
  final boolean isDelete=DELETE.equalsIgnoreCase(method);
  final boolean isPost=POST.equalsIgnoreCase(method);
  final boolean isPut=PUT.equalsIgnoreCase(method);
  byte[] excerpt=null;
  HttpRequestBase httpRequest;
  if (isPost || isPut) {
    HttpEntityEnclosingRequestBase entityEnclosingMethod=isPost ? new HttpPost(url) : new HttpPut(url);
    if (body != null) {
      ExcerptInputStream e=new ExcerptInputStream(body);
      excerpt=e.getExcerpt();
      String length=request.removeHeaders(HttpMessage.CONTENT_LENGTH);
      entityEnclosingMethod.setEntity(new InputStreamEntity(e,(length == null) ? -1 : Long.parseLong(length)));
    }
    httpRequest=entityEnclosingMethod;
  }
 else   if (isDelete) {
    httpRequest=new HttpDelete(url);
  }
 else {
    httpRequest=new HttpGet(url);
  }
  for (  Map.Entry<String,String> header : request.headers) {
    httpRequest.addHeader(header.getKey(),header.getValue());
  }
  HttpClient client=clientPool.getHttpClient(new URL(httpRequest.getURI().toString()));
  client.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS,false);
  HttpResponse httpResponse=client.execute(httpRequest);
  return new HttpMethodResponse(httpRequest,httpResponse,excerpt,request.getContentCharset());
}
 

Example 66

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

Source file: UriTexture.java

  16 
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 67

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

Source file: AudioBox.java

  16 
vote

/** 
 * Creates a HttpRequestBase
 * @param httpVerb the HTTP method to use for the request (ie: GET, PUT, POST and DELETE)
 * @param source usually reffers the Model that invokes method
 * @param dest Model that intercepts the response
 * @param action the remote action to execute on the model that executes the action (ex. "scrobble")
 * @param entity HttpEntity used by POST and PUT method
 * @return the HttpRequestBase 
 */
public HttpRequestBase createConnectionMethod(String httpVerb,String path,String action,ContentFormat format,List<NameValuePair> params){
  if (httpVerb == null) {
    httpVerb=IConnectionMethod.METHOD_GET;
  }
  String url=this.buildRequestUrl(path,action,httpVerb,format,params);
  HttpRequestBase method=null;
  if (IConnectionMethod.METHOD_POST.equals(httpVerb)) {
    log.debug("Building HttpMethod POST");
    method=new HttpPost(url);
  }
 else   if (IConnectionMethod.METHOD_PUT.equals(httpVerb)) {
    log.debug("Building HttpMethod PUT");
    method=new HttpPut(url);
  }
 else   if (IConnectionMethod.METHOD_DELETE.equals(httpVerb)) {
    log.debug("Building HttpMethod DELETE");
    method=new HttpDelete(url);
  }
 else {
    log.debug("Building HttpMethod GET");
    method=new HttpGet(url);
  }
  log.info("[ " + httpVerb + " ] "+ url);
  if (log.isDebugEnabled()) {
    log.debug("Setting default headers");
    log.debug("-> Accept-Encoding: gzip");
    log.debug("-> User-Agent: " + getConfiguration().getUserAgent());
  }
  method.addHeader("Accept-Encoding","gzip");
  method.addHeader("User-Agent",getConfiguration().getUserAgent());
  if (user != null && user.getAuthToken() != null) {
    method.addHeader(IConnector.X_AUTH_TOKEN_HEADER,user.getAuthToken());
    if (log.isDebugEnabled()) {
      log.debug("-> " + IConnector.X_AUTH_TOKEN_HEADER + ": ******"+ user.getAuthToken().substring(user.getAuthToken().length() - 5));
    }
  }
  return method;
}
 

Example 68

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

Source file: ImageLoader.java

  16 
vote

private Bitmap getBitmap(String url){
  File f=fileCache.getFile(url);
  Bitmap b=decodeFile(f);
  if (b != null)   return b;
  try {
    final HttpClient httpClient=HttpHelper.getHttpClient();
    final HttpResponse resp=httpClient.execute(new HttpGet(url));
    final HttpEntity entity=resp.getEntity();
    final int statusCode=resp.getStatusLine().getStatusCode();
    if (statusCode != HttpStatus.SC_OK || entity == null) {
      return null;
    }
    final byte[] respBytes=EntityUtils.toByteArray(entity);
    if (f != null) {
      try {
        FileOutputStream fos=new FileOutputStream(f);
        fos.write(respBytes);
        fos.close();
      }
 catch (      FileNotFoundException e) {
        Log.w(TAG,"Error writing to bitmap cache: " + f.toString(),e);
      }
catch (      IOException e) {
        Log.w(TAG,"Error writing to bitmap cache: " + f.toString(),e);
      }
    }
    Bitmap bitmap=decodeFile(f);
    return bitmap;
  }
 catch (  Exception ex) {
    Log.e(TAG,"Error retrieving image ",ex);
    return null;
  }
}
 

Example 69

From project android-sdk, under directory /src/test/java/com/mobeelizer/mobile/android/.

Source file: MobeelizerRealConnectionManagerTest.java

  15 
vote

@Test public void shouldAuthenticateAndReturnRole() throws Exception {
  when(httpEntity.getContent()).thenReturn(new ByteArrayInputStream("{'content':{'role':'role','instanceGuid':'0000'},'status':'OK'}".replaceAll("'","\"").getBytes()));
  MobeelizerLoginResponse response=connectionManager.login();
  verifyNew(HttpGet.class).withArguments("http://url/app/authenticate");
  verify(httpGet).setHeader("content-type","application/json");
  verify(httpGet).setHeader("mas-vendor-name","vendor");
  verify(httpGet).setHeader("mas-application-name","application");
  verify(httpGet).setHeader("mas-application-instance-name","instance");
  verify(httpGet).setHeader("mas-device-name","device");
  verify(httpGet).setHeader("mas-device-identifier","deviceIdentifier");
  verify(httpGet).setHeader("mas-user-name","user");
  verify(httpGet).setHeader("mas-user-password","password");
  verify(httpConnectionManager).shutdown();
  verify(database).setRoleAndInstanceGuid("instance","user","password","role","0000");
  assertEquals("role",response.getRole());
  assertEquals("0000",response.getInstanceGuid());
  assertNull(response.getError());
}
 

Example 70

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

Source file: CouchResponse.java

  15 
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 71

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

Source file: DownloadThread.java

  15 
vote

/** 
 * Fully execute a single download request - setup and send the request, handle the response, and transfer the data to the destination file.
 */
private void executeDownload(State state,AndroidHttpClient client,HttpGet request) throws StopRequest, RetryDownload {
  InnerState innerState=new InnerState();
  byte data[]=new byte[Constants.BUFFER_SIZE];
  setupDestinationFile(state,innerState);
  addRequestHeaders(innerState,request);
  checkConnectivity(state);
  HttpResponse response=sendRequest(state,client,request);
  handleExceptionalStatus(state,innerState,response);
  if (Constants.LOGV) {
    Log.v(Constants.TAG,"received response for " + mInfo.mUri);
  }
  processResponseHeaders(state,innerState,response);
  InputStream entityStream=openResponseEntity(state,response);
  transferData(state,innerState,data,entityStream);
}