Java Code Examples for org.apache.http.HttpStatus

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 adg-android, under directory /src/com/analysedesgeeks/android/service/impl/.

Source file: DownloadServiceImpl.java

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

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

Source file: WebResource.java

  15 
vote

/** 
 * Determine the size of this WebResource. <p> Note that the http client may read the entire file to determine this. </p>
 * @return the size of the file
 */
public int getSize(){
  HttpRequestBase method=new HttpHead(uri);
  HttpResponse response=null;
  try {
    response=client.execute(method);
    StatusLine statusLine=response.getStatusLine();
    if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
      return getHeaderAsInt(response,"Content-Length");
    }
    String reason=response.getStatusLine().getReasonPhrase();
    Reporter.informUser(this,JSMsg.gettext("Unable to find: {0}",reason + ':' + uri.getPath()));
  }
 catch (  IOException e) {
    return 0;
  }
  return 0;
}
 

Example 3

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

Source file: RSSReader.java

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

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

Source file: MobeelizerRealConnectionManagerTest.java

  15 
vote

@Test public void shouldReturnConnectionFailure() throws Exception {
  when(httpStatusLine.getStatusCode()).thenReturn(HttpStatus.SC_NOT_FOUND);
  when(database.getRoleAndInstanceGuid("instance","user","password")).thenReturn(new String[2]);
  MobeelizerLoginResponse response=connectionManager.login();
  assertNull(response.getRole());
  assertNull(response.getInstanceGuid());
  assertNotNull(response.getError());
}
 

Example 5

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

Source file: WebClient.java

  15 
vote

protected synchronized boolean deleteUrl(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);
  HttpDelete request=new HttpDelete(uri.getPath());
  request.setHeader("User-Agent",sUserAgent);
  try {
    HttpResponse response=client.execute(host,request);
    StatusLine status=response.getStatusLine();
    Log.i(cTag,"delete with response " + status.toString());
    return status.getStatusCode() == HttpStatus.SC_OK;
  }
 catch (  IOException e) {
    throw new ApiException("Problem communicating with API",e);
  }
}
 

Example 6

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

Source file: NetworkUtilities.java

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

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

Source file: BooksStore.java

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

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

Source file: JsonRequest.java

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

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

Source file: EasSyncService.java

  15 
vote

/** 
 * Send the POST command to the autodiscover server, handling a redirect, if necessary, and return the HttpResponse.  If we get a 401 (unauthorized) error and we're using the full email address, try the bare user name instead (e.g. foo instead of [email protected])
 * @param client the HttpClient to be used for the request
 * @param post the HttpPost we're going to send
 * @param canRetry whether we can retry using the bare name on an authentication failure (401)
 * @return an HttpResponse from the original or redirect server
 * @throws IOException on any IOException within the HttpClient code
 * @throws MessagingException
 */
private EasResponse postAutodiscover(HttpClient client,HttpPost post,boolean canRetry) throws IOException, MessagingException {
  userLog("Posting autodiscover to: " + post.getURI());
  EasResponse resp=executePostWithTimeout(client,post,COMMAND_TIMEOUT);
  int code=resp.getStatus();
  if (code == EAS_REDIRECT_CODE) {
    post=getRedirect(resp.mResponse,post);
    if (post != null) {
      userLog("Posting autodiscover to redirect: " + post.getURI());
      return executePostWithTimeout(client,post,COMMAND_TIMEOUT);
    }
  }
 else   if (code == HttpStatus.SC_UNAUTHORIZED) {
    if (canRetry && mUserName.contains("@")) {
      int atSignIndex=mUserName.indexOf('@');
      mUserName=mUserName.substring(0,atSignIndex);
      cacheAuthUserAndBaseUriStrings();
      userLog("401 received; trying username: ",mUserName);
      post.removeHeaders("Authorization");
      post.setHeader("Authorization",mAuthString);
      return postAutodiscover(client,post,false);
    }
    throw new MessagingException(MessagingException.AUTHENTICATION_FAILED);
  }
 else   if (code != HttpStatus.SC_OK) {
    userLog("Code: " + code + ", throwing IOException");
    throw new IOException();
  }
  return resp;
}
 

Example 10

From project apps-for-android, under directory /Photostream/src/com/google/android/photostream/.

Source file: Flickr.java

  15 
vote

/** 
 * Downloads the specified photo at the specified size in the specified destination.
 * @param photo The photo to download.
 * @param size The size of the photo to download.
 * @param destination The output stream in which to write the downloaded photo.
 * @throws IOException If any network exception occurs during the download.
 */
void downloadPhoto(Photo photo,PhotoSize size,OutputStream destination) throws IOException {
  final BufferedOutputStream out=new BufferedOutputStream(destination,IO_BUFFER_SIZE);
  final String url=photo.getUrl(size);
  final HttpGet get=new HttpGet(url);
  HttpEntity entity=null;
  try {
    final HttpResponse response=mClient.execute(get);
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
      entity=response.getEntity();
      entity.writeTo(out);
      out.flush();
    }
  }
  finally {
    if (entity != null) {
      entity.consumeContent();
    }
  }
}
 

Example 11

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

Source file: RemoteExecutor.java

  15 
vote

/** 
 * Execute this  {@link HttpUriRequest}, passing a valid response through {@link XmlHandler#parseAndApply(XmlPullParser,ContentResolver)}.
 */
public void execute(HttpUriRequest request,XmlHandler handler) throws HandlerException {
  try {
    final HttpResponse resp=mHttpClient.execute(request);
    final int status=resp.getStatusLine().getStatusCode();
    if (status != HttpStatus.SC_OK) {
      throw new HandlerException("Unexpected server response " + resp.getStatusLine() + " for "+ request.getRequestLine());
    }
    final InputStream input=resp.getEntity().getContent();
    try {
      final XmlPullParser parser=ParserUtils.newPullParser(input);
      handler.parseAndApply(parser,mResolver);
    }
 catch (    XmlPullParserException e) {
      throw new HandlerException("Malformed response for " + request.getRequestLine(),e);
    }
 finally {
      if (input != null)       input.close();
    }
  }
 catch (  HandlerException e) {
    throw e;
  }
catch (  IOException e) {
    throw new HandlerException("Problem reading remote response for " + request.getRequestLine(),e);
  }
}
 

Example 12

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

Source file: DefaultRequestMethod.java

  15 
vote

public Response getResponse() throws ServiceException, LoginException {
  try {
    Response response=this.futureResponse.get();
    this.running=false;
    this.aborted=false;
    if (response != null) {
      if (response.getException() != null) {
        AudioBoxException ex=response.getException();
        ex.setConfiguration(this.configuration);
        if (ex instanceof LoginException) {
          throw (LoginException)ex;
        }
 else {
          throw (ServiceException)ex;
        }
      }
      return response;
    }
  }
 catch (  InterruptedException e) {
    log.error("Request has been interrupted: " + getHttpMethod().getURI().toString());
    return null;
  }
catch (  CancellationException ce) {
    log.error("Request has been cancelled: " + getHttpMethod().getURI().toString());
    return null;
  }
catch (  ExecutionException e) {
    log.error("An error occurred while executing request",e);
    return null;
  }
  throw new ServiceException(HttpStatus.SC_PRECONDITION_FAILED,"No response");
}
 

Example 13

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

Source file: JoinServiceBase.java

  15 
vote

public int standardJoin(String joinUrl){
  joinedMeeting=new JoinedMeeting();
  try {
    HttpClient client=new DefaultHttpClient();
    HttpGet method=new HttpGet(joinUrl);
    HttpContext context=new BasicHttpContext();
    HttpResponse httpResponse=client.execute(method,context);
    if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK)     log.debug("HTTP GET {} return {}",joinUrl,httpResponse.getStatusLine().getStatusCode());
    HttpUriRequest currentReq=(HttpUriRequest)context.getAttribute(ExecutionContext.HTTP_REQUEST);
    if (!currentReq.getURI().getPath().equals("/client/BigBlueButton.html")) {
      log.error("It was redirected to {} instead of /client/BigBlueButton.html: the server was branded" + " and the HTML name was changed, or it's an error. However, it will continue processing",currentReq.getURI().getPath());
    }
    HttpHost currentHost=(HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    String enterUrl=currentHost.toURI() + "/bigbluebutton/api/enter";
    String enterResponse=getUrl(client,enterUrl).replace("</response>","<server>" + currentHost.toURI() + "</server></response>");
    joinedMeeting.parse(enterResponse);
  }
 catch (  Exception e) {
    e.printStackTrace();
    log.error("Can't join the url {}",joinUrl);
    return E_SERVER_UNREACHABLE;
  }
  return joinResponse();
}
 

Example 14

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

Source file: RSSReader.java

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

From project be.norio.twunch.android, under directory /src/com/google/android/apps/iosched/io/.

Source file: RemoteExecutor.java

  15 
vote

/** 
 * Execute this  {@link HttpUriRequest}, passing a valid response through {@link XmlHandler#parseAndApply(XmlPullParser,ContentResolver)}.
 */
public void execute(HttpUriRequest request,XmlHandler handler) throws HandlerException {
  try {
    final HttpResponse resp=mHttpClient.execute(request);
    final int status=resp.getStatusLine().getStatusCode();
    if (status != HttpStatus.SC_OK) {
      throw new HandlerException("Unexpected server response " + resp.getStatusLine() + " for "+ request.getRequestLine());
    }
    final InputStream input=resp.getEntity().getContent();
    try {
      final XmlPullParser parser=ParserUtils.newPullParser(input);
      handler.parseAndApply(parser,mResolver);
    }
 catch (    XmlPullParserException e) {
      throw new HandlerException("Malformed response for " + request.getRequestLine(),e);
    }
 finally {
      if (input != null)       input.close();
    }
  }
 catch (  HandlerException e) {
    throw e;
  }
catch (  IOException e) {
    throw new HandlerException("Problem reading remote response for " + request.getRequestLine(),e);
  }
}
 

Example 16

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

Source file: PriceService.java

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

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

Source file: ArtifactoryBuildInfoClient.java

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

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

Source file: Preferences.java

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

From project components-ness-httpserver_1, under directory /src/test/java/com/nesscomputing/httpserver/.

Source file: TestGuiceModule.java

  15 
vote

@Override protected void doGet(final HttpServletRequest req,final HttpServletResponse resp) throws ServletException, IOException {
  final Writer writer=resp.getWriter();
  resp.setStatus(HttpStatus.SC_OK);
  resp.setCharacterEncoding("ISO-8859-1");
  resp.setContentType("text/plain");
  writer.write(String.format("guice servlet: %s",magicUuid));
}
 

Example 20

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

Source file: RemoteExecutor.java

  15 
vote

/** 
 * Execute this  {@link HttpUriRequest}, passing a valid response through {@link XmlHandler#parseAndApply(XmlPullParser,ContentResolver)}.
 */
public void execute(HttpUriRequest request,XmlHandler handler) throws HandlerException {
  try {
    final HttpResponse resp=mHttpClient.execute(request);
    final int status=resp.getStatusLine().getStatusCode();
    if (status != HttpStatus.SC_OK) {
      throw new HandlerException("Unexpected server response " + resp.getStatusLine() + " for "+ request.getRequestLine());
    }
    final InputStream input=resp.getEntity().getContent();
    try {
      final XmlPullParser parser=ParserUtils.newPullParser(input);
      handler.parseAndApply(parser,mResolver);
    }
 catch (    XmlPullParserException e) {
      throw new HandlerException("Malformed response for " + request.getRequestLine(),e);
    }
 finally {
      if (input != null)       input.close();
    }
  }
 catch (  HandlerException e) {
    throw e;
  }
catch (  IOException e) {
    throw new HandlerException("Problem reading remote response for " + request.getRequestLine(),e);
  }
}
 

Example 21

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

Source file: Database.java

  15 
vote

public UUID getUuid() throws IOException, JSONException {
  try {
    final CouchDocument local=getDocument("_local/lucene");
    return UUID.fromString(local.asJson().getString("uuid"));
  }
 catch (  final HttpResponseException e) {
switch (e.getStatusCode()) {
case HttpStatus.SC_NOT_FOUND:
      return null;
default :
    throw e;
}
}
}
 

Example 22

From project crawler4j, under directory /src/test/java/edu/uci/ics/crawler4j/examples/localdata/.

Source file: Downloader.java

  15 
vote

private Page download(String url){
  WebURL curURL=new WebURL();
  curURL.setURL(url);
  PageFetchResult fetchResult=null;
  try {
    fetchResult=pageFetcher.fetchHeader(curURL);
    if (fetchResult.getStatusCode() == HttpStatus.SC_OK) {
      try {
        Page page=new Page(curURL);
        fetchResult.fetchContent(page);
        if (parser.parse(page,curURL.getURL())) {
          return page;
        }
      }
 catch (      Exception e) {
        e.printStackTrace();
      }
    }
  }
  finally {
    fetchResult.discardContentIfNotConsumed();
  }
  return null;
}
 

Example 23

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

Source file: RemoteExecutor.java

  15 
vote

/** 
 * Execute this  {@link HttpUriRequest}, passing a valid response through {@link XmlHandler#parseAndApply(XmlPullParser,ContentResolver)}.
 */
public void execute(HttpUriRequest request,XmlHandler handler) throws HandlerException {
  try {
    final HttpResponse resp=mHttpClient.execute(request);
    final int status=resp.getStatusLine().getStatusCode();
    if (status != HttpStatus.SC_OK) {
      throw new HandlerException("Unexpected server response " + resp.getStatusLine() + " for "+ request.getRequestLine());
    }
    final InputStream input=resp.getEntity().getContent();
    try {
      final XmlPullParser parser=ParserUtils.newPullParser(input);
      handler.parseAndApply(parser,mResolver);
    }
 catch (    XmlPullParserException e) {
      throw new HandlerException("Malformed response for " + request.getRequestLine(),e);
    }
 finally {
      if (input != null)       input.close();
    }
  }
 catch (  HandlerException e) {
    throw e;
  }
catch (  IOException e) {
    throw new HandlerException("Problem reading remote response for " + request.getRequestLine(),e);
  }
}
 

Example 24

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

Source file: RemoteExecutor.java

  15 
vote

/** 
 * Execute this  {@link HttpUriRequest}, passing a valid response through {@link XmlHandler#parseAndApply(XmlPullParser,ContentResolver)}.
 */
public void execute(HttpUriRequest request,XmlHandler handler) throws HandlerException {
  try {
    final HttpResponse resp=mHttpClient.execute(request);
    final int status=resp.getStatusLine().getStatusCode();
    if (status != HttpStatus.SC_OK) {
      throw new HandlerException("Unexpected server response " + resp.getStatusLine() + " for "+ request.getRequestLine());
    }
    final InputStream input=resp.getEntity().getContent();
    try {
      final XmlPullParser parser=ParserUtils.newPullParser(input);
      handler.parseAndApply(parser,mResolver);
    }
 catch (    XmlPullParserException e) {
      throw new HandlerException("Malformed response for " + request.getRequestLine(),e);
    }
 finally {
      if (input != null)       input.close();
    }
  }
 catch (  HandlerException e) {
    throw e;
  }
catch (  IOException e) {
    throw new HandlerException("Problem reading remote response for " + request.getRequestLine(),e);
  }
}
 

Example 25

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

Source file: DeliciousFeed.java

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

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

Source file: RemoteJsonExecutor.java

  15 
vote

private void execute(HttpUriRequest request,JsonHandler handler) throws HandlerException {
  try {
    final HttpResponse resp=mHttpClient.execute(request);
    final int status=resp.getStatusLine().getStatusCode();
    if (status != HttpStatus.SC_OK) {
      throw new HandlerException("Unexpected server response " + resp.getStatusLine() + " for "+ request.getRequestLine());
    }
    final InputStream input=resp.getEntity().getContent();
    try {
      handler.parseAndApply(input,mResolver);
    }
  finally {
      if (input != null)       input.close();
    }
  }
 catch (  HandlerException e) {
    throw e;
  }
catch (  IOException e) {
    throw new HandlerException("Problem reading remote response for " + request.getRequestLine(),e);
  }
}
 

Example 27

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

Source file: RSSReader.java

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

From project emite, under directory /src/test/java/com/calclab/emite/xtesting/services/.

Source file: HttpConnector.java

  15 
vote

private Runnable createResponseAction(final String xml,final ConnectorCallback callback,final String id,final int status,final String response){
  final Runnable runnable=new Runnable(){
    @Override public void run(){
      if (status == HttpStatus.SC_OK) {
        System.out.println("RECEIVED: " + response);
        debug("Connector [{0}] receive: {1}",id,response);
        callback.onResponseReceived(status,response,xml);
      }
 else {
        debug("Connector [{0}] bad status: {1}",id,status);
        callback.onResponseError(xml,new Exception("bad http status " + status));
      }
    }
  }
;
  return runnable;
}
 

Example 29

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

Source file: Axis2HttpWorker.java

  15 
vote

private void handleServicesList(final AxisHttpResponse response,final ConfigurationContext configurationContext) throws IOException {
  String s=HTTPTransportReceiver.getServicesHTML(configurationContext);
  response.setStatus(HttpStatus.SC_OK);
  response.setContentType("text/html");
  OutputStream out=response.getOutputStream();
  out.write(EncodingUtils.getBytes(s,HTTP.ISO_8859_1));
}
 

Example 30

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

Source file: ImageHelper.java

  15 
vote

static Bitmap downloadBitmap(String url){
  final DefaultHttpClient client=new DefaultHttpClient();
  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();
        Bitmap bitmap=BitmapFactory.decodeStream(inputStream);
        BitmapDrawable bd=new BitmapDrawable(bitmap);
        bitmap=com.commonsware.cwac.thumbnail.ThumbnailAdapter.getRoundedCornerBitmap(bd.getBitmap());
        return bitmap;
      }
  finally {
        if (inputStream != null) {
          inputStream.close();
        }
        entity.consumeContent();
      }
    }
  }
 catch (  Exception e) {
    getRequest.abort();
    Log.w("ImageDownloader","Error while retrieving bitmap from " + url);
  }
  return null;
}
 

Example 31

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

Source file: AndroidAssets.java

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

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

Source file: RemoteExecutor.java

  15 
vote

/** 
 * Execute this  {@link HttpUriRequest}, passing a valid response through {@link XmlHandler#parseAndApply(XmlPullParser,ContentResolver)}.
 */
public void execute(HttpUriRequest request,XmlHandler handler) throws HandlerException {
  try {
    final HttpResponse resp=mHttpClient.execute(request);
    final int status=resp.getStatusLine().getStatusCode();
    if (status != HttpStatus.SC_OK) {
      throw new HandlerException("Unexpected server response " + resp.getStatusLine() + " for "+ request.getRequestLine());
    }
    final InputStream input=resp.getEntity().getContent();
    try {
      final XmlPullParser parser=ParserUtils.newPullParser(input);
      handler.parseAndApply(parser,mResolver);
    }
 catch (    XmlPullParserException e) {
      throw new HandlerException("Malformed response for " + request.getRequestLine(),e);
    }
 finally {
      if (input != null)       input.close();
    }
  }
 catch (  HandlerException e) {
    throw e;
  }
catch (  IOException e) {
    throw new HandlerException("Problem reading remote response for " + request.getRequestLine(),e);
  }
}
 

Example 33

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

Source file: URLContentLoader.java

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

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

Source file: onlineService2Provider.java

  15 
vote

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

Example 35

From project HSR-Timetable, under directory /HSRTimeTable/src/ch/scythe/hsr/api/.

Source file: TimeTableAPI.java

  15 
vote

public boolean validateCredentials(String login,String password) throws ServerConnectionException {
  boolean result=false;
  try {
    HttpGet get=createHttpGet(URL + METHOD_GET_TIMEPERIOD,login,password);
    HttpClient httpclient=new DefaultHttpClient();
    BasicHttpResponse httpResponse=(BasicHttpResponse)httpclient.execute(get);
    int httpStatus=httpResponse.getStatusLine().getStatusCode();
    result=HttpStatus.SC_OK == httpStatus;
  }
 catch (  Exception e) {
    throw new ServerConnectionException(e);
  }
  return result;
}
 

Example 36

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

Source file: DefaultProxyAuthenticationHandler.java

  15 
vote

public boolean isAuthenticationRequested(final HttpResponse response,final HttpContext context){
  if (response == null) {
    throw new IllegalArgumentException("HTTP response may not be null");
  }
  int status=response.getStatusLine().getStatusCode();
  return status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED;
}