Java Code Examples for org.apache.http.StatusLine

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 build-info, under directory /build-info-client/src/main/java/org/jfrog/build/client/.

Source file: ArtifactoryBuildInfoClient.java

  22 
vote

private void uploadFile(DeployDetails details,String uploadUrl) throws IOException {
  if (tryChecksumDeploy(details,uploadUrl)) {
    return;
  }
  HttpPut httpPut=createHttpPutMethod(details,uploadUrl);
  httpPut.addHeader(HTTP.EXPECT_DIRECTIVE,HTTP.EXPECT_CONTINUE);
  FileEntity fileEntity=new FileEntity(details.file,"binary/octet-stream");
  StatusLine statusLine=httpClient.upload(httpPut,fileEntity);
  int statusCode=statusLine.getStatusCode();
  if ((statusCode != HttpStatus.SC_CREATED) && (statusCode != HttpStatus.SC_OK)) {
    throwHttpIOException("Failed to deploy file:",statusLine);
  }
}
 

Example 2

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

Source file: InternalResponse.java

  22 
vote

@Override public int getStatusCode(){
  if (httpResponse != null) {
    final StatusLine statusLine=httpResponse.getStatusLine();
    return (statusLine == null) ? 0 : statusLine.getStatusCode();
  }
  return 0;
}
 

Example 3

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

Source file: StubHttpClient.java

  22 
vote

/** 
 * Build a stub  {@link HttpResponse}, probably for use with {@link #setResponse(HttpResponse)}.
 * @param statusCode {@link HttpStatus} code to use.
 * @param assetName Name of asset that should be included as a single{@link HttpEntity} to be included in the response, loadedthrough  {@link AssetManager}.
 */
public static HttpResponse buildResponse(int statusCode,String assetName,Context context) throws IOException {
  final StatusLine status=new BasicStatusLine(HttpVersion.HTTP_1_1,statusCode,null);
  final HttpResponse response=new BasicHttpResponse(status);
  if (assetName != null) {
    final InputStream entity=context.getAssets().open(assetName);
    response.setEntity(new InputStreamEntity(entity,entity.available()));
  }
  return response;
}
 

Example 4

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

Source file: ErrorPreservingResponseHandler.java

  22 
vote

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

Example 5

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

Source file: ByteArrayResponseHandler.java

  22 
vote

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

Example 6

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

Source file: ByteArrayResponseHandler.java

  22 
vote

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

Example 7

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

Source file: StubHttpClient.java

  22 
vote

/** 
 * Build a stub  {@link HttpResponse}, probably for use with {@link #setResponse(HttpResponse)}.
 * @param statusCode {@link HttpStatus} code to use.
 * @param assetName Name of asset that should be included as a single{@link HttpEntity} to be included in the response, loadedthrough  {@link AssetManager}.
 */
public static HttpResponse buildResponse(int statusCode,String assetName,Context context) throws IOException {
  final StatusLine status=new BasicStatusLine(HttpVersion.HTTP_1_1,statusCode,null);
  final HttpResponse response=new BasicHttpResponse(status);
  if (assetName != null) {
    final InputStream entity=context.getAssets().open(assetName);
    response.setEntity(new InputStreamEntity(entity,entity.available()));
  }
  return response;
}
 

Example 8

From project dcnyc10-android, under directory /android/tests.old/src/com/google/android/apps/iosched/io/.

Source file: StubHttpClient.java

  22 
vote

/** 
 * Build a stub  {@link HttpResponse}, probably for use with {@link #setResponse(HttpResponse)}.
 * @param statusCode {@link HttpStatus} code to use.
 * @param assetName Name of asset that should be included as a single{@link HttpEntity} to be included in the response, loadedthrough  {@link AssetManager}.
 */
public static HttpResponse buildResponse(int statusCode,String assetName,Context context) throws IOException {
  final StatusLine status=new BasicStatusLine(HttpVersion.HTTP_1_1,statusCode,null);
  final HttpResponse response=new BasicHttpResponse(status);
  if (assetName != null) {
    final InputStream entity=context.getAssets().open(assetName);
    response.setEntity(new InputStreamEntity(entity,entity.available()));
  }
  return response;
}
 

Example 9

From project gddsched2, under directory /trunk/android/tests.old/src/com/google/android/apps/iosched/io/.

Source file: StubHttpClient.java

  22 
vote

/** 
 * Build a stub  {@link HttpResponse}, probably for use with {@link #setResponse(HttpResponse)}.
 * @param statusCode {@link HttpStatus} code to use.
 * @param assetName Name of asset that should be included as a single{@link HttpEntity} to be included in the response, loadedthrough  {@link AssetManager}.
 */
public static HttpResponse buildResponse(int statusCode,String assetName,Context context) throws IOException {
  final StatusLine status=new BasicStatusLine(HttpVersion.HTTP_1_1,statusCode,null);
  final HttpResponse response=new BasicHttpResponse(status);
  if (assetName != null) {
    final InputStream entity=context.getAssets().open(assetName);
    response.setEntity(new InputStreamEntity(entity,entity.available()));
  }
  return response;
}
 

Example 10

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

Source file: ContentResponseHandler.java

  22 
vote

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

Example 11

From project httpcore, under directory /httpcore/src/main/java/org/apache/http/impl/.

Source file: DefaultHttpResponseFactory.java

  22 
vote

public HttpResponse newHttpResponse(final ProtocolVersion ver,final int status,HttpContext context){
  Args.notNull(ver,"HTTP version");
  Locale loc=determineLocale(context);
  String reason=reasonCatalog.getReason(status,loc);
  StatusLine statusline=new BasicStatusLine(ver,status,reason);
  return new BasicHttpResponse(statusline,reasonCatalog,loc);
}
 

Example 12

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

Source file: StubHttpClient.java

  22 
vote

/** 
 * Build a stub  {@link HttpResponse}, probably for use with {@link #setResponse(HttpResponse)}.
 * @param statusCode {@link HttpStatus} code to use.
 * @param assetName Name of asset that should be included as a single{@link HttpEntity} to be included in the response, loadedthrough  {@link AssetManager}.
 */
public static HttpResponse buildResponse(int statusCode,String assetName,Context context) throws IOException {
  final StatusLine status=new BasicStatusLine(HttpVersion.HTTP_1_1,statusCode,null);
  final HttpResponse response=new BasicHttpResponse(status);
  if (assetName != null) {
    final InputStream entity=context.getAssets().open(assetName);
    response.setEntity(new InputStreamEntity(entity,entity.available()));
  }
  return response;
}
 

Example 13

From project iosched2011, under directory /android/tests.old/src/com/google/android/apps/iosched/io/.

Source file: StubHttpClient.java

  22 
vote

/** 
 * Build a stub  {@link HttpResponse}, probably for use with {@link #setResponse(HttpResponse)}.
 * @param statusCode {@link HttpStatus} code to use.
 * @param assetName Name of asset that should be included as a single{@link HttpEntity} to be included in the response, loadedthrough  {@link AssetManager}.
 */
public static HttpResponse buildResponse(int statusCode,String assetName,Context context) throws IOException {
  final StatusLine status=new BasicStatusLine(HttpVersion.HTTP_1_1,statusCode,null);
  final HttpResponse response=new BasicHttpResponse(status);
  if (assetName != null) {
    final InputStream entity=context.getAssets().open(assetName);
    response.setEntity(new InputStreamEntity(entity,entity.available()));
  }
  return response;
}
 

Example 14

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

Source file: StubHttpClient.java

  22 
vote

/** 
 * Build a stub  {@link HttpResponse}, probably for use with {@link #setResponse(HttpResponse)}.
 * @param statusCode {@link HttpStatus} code to use.
 * @param assetName Name of asset that should be included as a single{@link HttpEntity} to be included in the response, loadedthrough  {@link AssetManager}.
 */
public static HttpResponse buildResponse(int statusCode,String assetName,Context context) throws IOException {
  final StatusLine status=new BasicStatusLine(HttpVersion.HTTP_1_1,statusCode,null);
  final HttpResponse response=new BasicHttpResponse(status);
  if (assetName != null) {
    final InputStream entity=context.getAssets().open(assetName);
    response.setEntity(new InputStreamEntity(entity,entity.available()));
  }
  return response;
}
 

Example 15

From project iosched_2, under directory /android/tests.old/src/com/google/android/apps/iosched/io/.

Source file: StubHttpClient.java

  22 
vote

/** 
 * Build a stub  {@link HttpResponse}, probably for use with {@link #setResponse(HttpResponse)}.
 * @param statusCode {@link HttpStatus} code to use.
 * @param assetName Name of asset that should be included as a single{@link HttpEntity} to be included in the response, loadedthrough  {@link AssetManager}.
 */
public static HttpResponse buildResponse(int statusCode,String assetName,Context context) throws IOException {
  final StatusLine status=new BasicStatusLine(HttpVersion.HTTP_1_1,statusCode,null);
  final HttpResponse response=new BasicHttpResponse(status);
  if (assetName != null) {
    final InputStream entity=context.getAssets().open(assetName);
    response.setEntity(new InputStreamEntity(entity,entity.available()));
  }
  return response;
}
 

Example 16

From project OpenTripPlanner, under directory /opentripplanner-utils/src/main/java/org/opentripplanner/util/.

Source file: HttpUtils.java

  22 
vote

public static void testUrl(String url) throws ClientProtocolException, IOException {
  HttpHead head=new HttpHead(url);
  HttpClient httpclient=new DefaultHttpClient();
  HttpResponse response=httpclient.execute(head);
  StatusLine status=response.getStatusLine();
  if (status.getStatusCode() == 404) {
    throw new FileNotFoundException();
  }
  if (status.getStatusCode() != 200) {
    throw new RuntimeException("Could not get URL: " + status.getStatusCode() + ": "+ status.getReasonPhrase());
  }
}
 

Example 17

From project platform_external_apache-http, under directory /src/org/apache/http/impl/client/.

Source file: BasicResponseHandler.java

  22 
vote

/** 
 * Returns the response body as a String if the response was successful (a 2xx status code). If no response body exists, this returns null. If the response was unsuccessful (>= 300 status code), throws an {@link HttpResponseException}.
 */
public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
  StatusLine statusLine=response.getStatusLine();
  if (statusLine.getStatusCode() >= 300) {
    throw new HttpResponseException(statusLine.getStatusCode(),statusLine.getReasonPhrase());
  }
  HttpEntity entity=response.getEntity();
  return entity == null ? null : EntityUtils.toString(entity);
}
 

Example 18

From project platform_frameworks_support, under directory /volley/tests/src/com/android/volley/mock/.

Source file: MockHttpClient.java

  22 
vote

@Override public HttpResponse execute(HttpUriRequest request,HttpContext context){
  requestExecuted=request;
  StatusLine statusLine=new BasicStatusLine(new ProtocolVersion("HTTP",1,1),mStatusCode,"");
  HttpResponse response=new BasicHttpResponse(statusLine);
  response.setEntity(mResponseEntity);
  return response;
}
 

Example 19

From project signpost, under directory /signpost-commonshttp4/src/test/java/oauth/signpost/commonshttp/.

Source file: CommonHttpOAuthProviderMock.java

  22 
vote

public void mockConnection(String responseBody) throws Exception {
  HttpResponse response=mock(HttpResponse.class);
  this.httpClientMock=mock(HttpClient.class);
  InputStream is=new ByteArrayInputStream(responseBody.getBytes());
  InputStreamEntity entity=new InputStreamEntity(is,responseBody.length());
  StatusLine statusLine=new BasicStatusLine(new ProtocolVersion("HTTP",1,1),200,"OK");
  when(response.getStatusLine()).thenReturn(statusLine);
  when(response.getEntity()).thenReturn(entity);
  when(httpClientMock.execute(Mockito.any(HttpUriRequest.class))).thenReturn(response);
}
 

Example 20

From project spring-insight-plugins, under directory /collection-plugins/httpclient4/src/test/java/com/springsource/insight/plugin/apache/http/hc4/.

Source file: HttpClientExecutionCollectionAspectTest.java

  22 
vote

private OperationMap assertResponseDetails(String uri,OperationMap details,HttpResponse response,boolean checkHeaders){
  if (response == null) {
    return details;
  }
  StatusLine statusLine=response.getStatusLine();
  assertEquals("Mismatched status code",Integer.valueOf(statusLine.getStatusCode()),details.get("statusCode"));
  assertEquals("Mismatched reason phrase",statusLine.getReasonPhrase(),details.get("reasonPhrase"));
  if (checkHeaders) {
    assertHeadersContents(uri,"response",details,response);
  }
  return details;
}
 

Example 21

From project Vega, under directory /platform/com.subgraph.vega.ui.httpeditor/src/com/subgraph/vega/ui/httpeditor/parser/.

Source file: HttpResponseParser.java

  22 
vote

/** 
 * Read and parse the response line.
 * @param parser HC LineParser.
 * @param builder HTTP response builder.
 * @param buf
 * @param bufCursor
 * @return
 */
private int parseStatusLine(final LineParser parser,final IHttpResponseBuilder builder,final CharArrayBuffer buf,final ParserCursor bufCursor){
  final CharArrayBuffer lnBuf=new CharArrayBuffer(0);
  if (readLine(buf,bufCursor,lnBuf) < 1) {
    return -1;
  }
  final ParserCursor lnCursor=new ParserCursor(0,lnBuf.length());
  final StatusLine statusLine=parser.parseStatusLine(lnBuf,lnCursor);
  builder.setFromStatusLine(statusLine);
  return 0;
}
 

Example 22

From project zen-project, under directory /zen-webservice/src/main/java/com/nominanuda/web/http/.

Source file: HttpCoreHelper.java

  22 
vote

public HttpResponse redirectTo(String url){
  StatusLine statusline=statusLine(302);
  HttpResponse resp=new BasicHttpResponse(statusline);
  resp.addHeader(HDR_LOCATION,url);
  return resp;
}
 

Example 23

From project zirco-browser, under directory /src/org/emergent/android/weave/client/.

Source file: WeaveTransport.java

  22 
vote

/** 
 * Returns the response body as a String if the response was successful (a 2xx status code). If no response body exists, this returns null. If the response was unsuccessful (>= 300 status code), throws an {@link org.apache.http.client.HttpResponseException}.
 */
public WeaveResponse handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
  StatusLine statusLine=response.getStatusLine();
  if (statusLine.getStatusCode() >= 300) {
    throw new WeaveResponseException(statusLine.getStatusCode(),statusLine.getReasonPhrase(),response);
  }
  return new WeaveResponse(response);
}
 

Example 24

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

Source file: DownloadServiceImpl.java

  21 
vote

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

Example 25

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

Source file: WebResource.java

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

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

Source file: AsyncHttpResponseHandler.java

  21 
vote

void sendResponseMessage(HttpResponse response){
  StatusLine status=response.getStatusLine();
  String responseBody=null;
  try {
    HttpEntity entity=null;
    HttpEntity temp=response.getEntity();
    if (temp != null) {
      entity=new BufferedHttpEntity(temp);
      responseBody=EntityUtils.toString(entity,"UTF-8");
    }
  }
 catch (  IOException e) {
    sendFailureMessage(e,(String)null);
  }
  if (status.getStatusCode() >= 300) {
    sendFailureMessage(new HttpResponseException(status.getStatusCode(),status.getReasonPhrase()),responseBody);
  }
 else {
    sendSuccessMessage(responseBody);
  }
}
 

Example 27

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

Source file: RSSReader.java

  21 
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 android-shuffle, under directory /client/src/org/dodgybits/shuffle/android/synchronisation/tracks/.

Source file: WebClient.java

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

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

Source file: WebserviceTask.java

  21 
vote

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

Example 30

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

Source file: VeecheckThread.java

  21 
vote

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

Example 31

From project artifactory-plugin, under directory /src/main/java/org/jfrog/hudson/release/.

Source file: PromoteBuildAction.java

  21 
vote

/** 
 * Checks the status and return true on success
 * @param response
 * @param dryRun
 * @param parseMessages
 * @param listener
 * @return
 */
private boolean checkSuccess(HttpResponse response,boolean dryRun,boolean parseMessages,TaskListener listener){
  StatusLine status=response.getStatusLine();
  try {
    String content=entityToString(response);
    if (assertResponseStatus(dryRun,listener,status,content)) {
      if (parseMessages) {
        JSONObject json=JSONObject.fromObject(content);
        JSONArray messages=json.getJSONArray("messages");
        for (        Object messageObj : messages) {
          JSONObject messageJson=(JSONObject)messageObj;
          String level=messageJson.getString("level");
          String message=messageJson.getString("message");
          if ((level.equals("WARNING") || level.equals("ERROR")) && !message.startsWith("No items were")) {
            listener.error("Received " + level + ": "+ message);
            return false;
          }
        }
      }
      return true;
    }
  }
 catch (  IOException e) {
    e.printStackTrace(listener.error("Failed parsing promotion response:"));
  }
  return false;
}
 

Example 32

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

Source file: RSSReader.java

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

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

Source file: PriceService.java

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

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

Source file: Chargify.java

  21 
vote

protected String handleResponseCode(HttpResponse response,HttpRequestBase method) throws ChargifyException {
  StatusLine line=response.getStatusLine();
  String errorMsg=method.getMethod() + " " + String.valueOf(method.getURI())+ " Error "+ String.valueOf(line.getStatusCode())+ " "+ line.getReasonPhrase();
  int code=line.getStatusCode();
  if (isError(code)) {
    try {
      Errors error=(Errors)parse(Errors.class,response,method);
      if (error != null) {
        errorMsg=String.valueOf(error) + ". Method " + errorMsg;
      }
    }
 catch (    Exception ex) {
      errorMsg+=" " + ex.getMessage() + " "+ ex.getStackTrace()[0];
    }
  }
  return handleResponse(code,errorMsg);
}
 

Example 35

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

Source file: HttpClientDirectMemoryHttpClient.java

  21 
vote

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

Example 36

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

Source file: RSSReader.java

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

From project FlickrCity, under directory /src/com/FlickrCity/FlickrCityAndroid/Activities/.

Source file: PhotoActivity.java

  21 
vote

private FlickrPhoto getFlickrPhotoByID(String photo_id){
  String url="http://api.flickr.com/services/rest/?method=flickr.photos.getInfo" + "&api_key=" + Constants.API_KEY + "&photo_id="+ photo_id+ "&format=json&nojsoncallback=1";
  String json_response=null;
  try {
    HttpClient client=new DefaultHttpClient();
    HttpGet httpGet=new HttpGet(url);
    HttpResponse response=client.execute(httpGet);
    StatusLine statusLine=response.getStatusLine();
    int statusCode=statusLine.getStatusCode();
    if (statusCode == 200) {
      json_response=EntityUtils.toString(response.getEntity());
    }
  }
 catch (  Exception e) {
  }
  if (json_response == null)   return null;
 else {
    final FlickrPhoto photo=new FlickrPhoto();
    try {
      JSONObject jobj=new JSONObject(json_response);
      photo.setOwner(jobj.getJSONObject("photo").getJSONObject("owner").getString("username"));
      photo.setTitle(jobj.getJSONObject("photo").getJSONObject("title").getString("_content"));
    }
 catch (    Exception e) {
    }
    return photo;
  }
}
 

Example 38

From project Fotolia-API, under directory /java/org/webservice/fotolia/.

Source file: FotoliaApiResponse.java

  21 
vote

/** 
 * Returns the response body as a String if the response was successful (a 2xx status code). If no response body exists, this returns null. If the response was unsuccessful (>= 300 status code), throws an {@link HttpResponseException}.
 */
public String handleResponse(final HttpResponse response) throws FotoliaApiException, IOException {
  StatusLine statusLine=response.getStatusLine();
  HttpEntity entity=response.getEntity();
  JSONObject obj;
  String error_msg;
  int error_code;
  if (statusLine.getStatusCode() != 200) {
    if (entity == null) {
      throw new HttpResponseException(statusLine.getStatusCode(),statusLine.getReasonPhrase());
    }
 else {
      obj=(JSONObject)JSONValue.parse(EntityUtils.toString(entity));
      error_msg=(String)obj.get("error");
      if (obj.get("code") != null) {
        error_code=Integer.parseInt((String)obj.get("code"));
      }
 else {
        error_code=statusLine.getStatusCode();
      }
      throw new FotoliaApiException(error_code,error_msg);
    }
  }
  return entity == null ? null : EntityUtils.toString(entity);
}
 

Example 39

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

Source file: SimpleWikiHelper.java

  21 
vote

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

Example 40

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

Source file: onlineService2Provider.java

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

From project jsword, under directory /src/main/java/org/crosswire/common/util/.

Source file: WebResource.java

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

From project lilith, under directory /lilith/src/main/java/de/huxhorn/lilith/swing/.

Source file: MainFrame.java

  21 
vote

private static String readUrl(String url){
  final Logger logger=LoggerFactory.getLogger(MainFrame.class);
  DefaultHttpClient client=new DefaultHttpClient();
  HttpContext localContext=new BasicHttpContext();
  HttpGet httpget=new HttpGet(url);
  try {
    HttpResponse response=client.execute(httpget,localContext);
    StatusLine status=response.getStatusLine();
    if (status.getStatusCode() != HttpStatus.OK.getCode()) {
      if (logger.isWarnEnabled())       logger.warn("Status while retrieving '{}': {}",url,status);
      return null;
    }
    HttpEntity entity=response.getEntity();
    String result=EntityUtils.toString(entity);
    EntityUtils.consume(entity);
    return result;
  }
 catch (  IOException e) {
    if (logger.isWarnEnabled())     logger.warn("Exception while retrieving '" + url + "'!",e);
    return null;
  }
 finally {
    client.getConnectionManager().shutdown();
  }
}
 

Example 43

From project LitHub, under directory /LitHub-Android/src/us/lithub/appengine/.

Source file: AccountsActivity.java

  21 
vote

/** 
 * Retrieves the authorization cookie associated with the given token. This method should only be used when running against a production appengine backend (as opposed to a dev mode server).
 */
private String getAuthCookie(String authToken){
  DefaultHttpClient httpClient=new DefaultHttpClient();
  try {
    httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS,false);
    String uri=Setup.PROD_URL + "/_ah/login?continue=http://localhost/&auth=" + authToken;
    HttpGet method=new HttpGet(uri);
    HttpResponse res=httpClient.execute(method);
    StatusLine statusLine=res.getStatusLine();
    int statusCode=statusLine.getStatusCode();
    Header[] headers=res.getHeaders("Set-Cookie");
    if (statusCode != 302 || headers.length == 0) {
      return null;
    }
    for (    Cookie cookie : httpClient.getCookieStore().getCookies()) {
      if (AUTH_COOKIE_NAME.equals(cookie.getName())) {
        return AUTH_COOKIE_NAME + "=" + cookie.getValue();
      }
    }
  }
 catch (  IOException e) {
    Log.w(TAG,"Got IOException " + e);
    Log.w(TAG,Log.getStackTraceString(e));
  }
 finally {
    httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS,true);
  }
  return null;
}
 

Example 44

From project meaningfulweb, under directory /meaningfulweb-core/src/main/java/org/meaningfulweb/util/http/.

Source file: HttpComponentsServiceImpl.java

  21 
vote

@Override public HttpResponse doHead(HttpHead httpget) throws HttpException {
  if (!active.get()) {
    return null;
  }
  try {
    HttpResponse response=httpClient.execute(httpget);
    StatusLine status=response.getStatusLine();
    int statusCode=status.getStatusCode();
    if (statusCode >= 400) {
      throw new HttpException(statusCode,httpget.getURI() + ":" + status.getReasonPhrase());
    }
    return response;
  }
 catch (  HttpException he) {
    throw he;
  }
catch (  Exception e) {
    LOG.error("Error getting url: " + httpget.getURI(),e);
    httpget.abort();
    throw new HttpException(e);
  }
}
 

Example 45

From project OAuth2Android, under directory /src/org/gerstner/oauth2android/response/.

Source file: Response.java

  21 
vote

private boolean initialAnalysis() throws JSONException, InvalidRequestException, InvalidClientException, InvalidGrantException, UnauthorizedClientException, UnsupportedGrantTypeException, InvalidScopeException, OAuthException {
  StatusLine statusLine=this.httpResponse.getStatusLine();
  this.statusCode=statusLine.getStatusCode();
  try {
    getStringEntity();
  }
 catch (  IOException ex) {
    Logger.getLogger(Response.class.getName()).log(Level.SEVERE,null,ex);
  }
  if (parseStringEntityForJson()) {
    JsonParser.parseForErrors(jsonResponse);
  }
 else   if (parseStringEntityForParameters()) {
  }
switch (statusCode) {
case (200):
{
      return true;
    }
case (401):
{
    OAuthException unauthorizedClientException=new UnauthorizedClientException(statusLine.getReasonPhrase());
    unauthorizedClientException.setErrorDescription(this.httpResponse.getFirstHeader("WWW-Authenticate").getValue());
    return false;
  }
}
return true;
}
 

Example 46

From project picketbox-http, under directory /src/test/java/org/picketbox/test/authentication/http/jetty/.

Source file: DelegatingSecurityFilterHTTPBasicUnitTestCase.java

  21 
vote

@Test public void testBasicAuth() throws Exception {
  URL url=new URL(urlStr);
  DefaultHttpClient httpclient=null;
  try {
    String user="Aladdin";
    String pass="Open Sesame";
    httpclient=new DefaultHttpClient();
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(),url.getPort()),new UsernamePasswordCredentials(user,pass));
    HttpGet httpget=new HttpGet(url.toExternalForm());
    System.out.println("executing request" + httpget.getRequestLine());
    HttpResponse response=httpclient.execute(httpget);
    HttpEntity entity=response.getEntity();
    System.out.println("----------------------------------------");
    StatusLine statusLine=response.getStatusLine();
    System.out.println(statusLine);
    if (entity != null) {
      System.out.println("Response content length: " + entity.getContentLength());
    }
    assertEquals(200,statusLine.getStatusCode());
    EntityUtils.consume(entity);
  }
  finally {
    httpclient.getConnectionManager().shutdown();
  }
}
 

Example 47

From project sched-assist, under directory /sched-assist-spi-caldav/src/test/java/org/jasig/schedassist/impl/caldav/.

Source file: CaldavCalendarDataDaoImplTest.java

  21 
vote

@Test public void testGetCalendarProblem1() throws ClientProtocolException, IOException {
  java.util.Date now=new java.util.Date();
  java.util.Date later=DateUtils.addDays(now,1);
  CaldavCalendarDataDaoImpl calendarDataDao=new CaldavCalendarDataDaoImpl();
  ICalendarAccount calendarAccount=mock(ICalendarAccount.class);
  when(calendarAccount.getUsername()).thenReturn("username");
  when(calendarAccount.getEmailAddress()).thenReturn("[email protected]");
  DefaultCaldavDialectImpl dialect=new DefaultCaldavDialectImpl();
  dialect.setCaldavHost(URI.create("http://localhost:8080/"));
  calendarDataDao.setCaldavDialect(dialect);
  DefaultCredentialsProviderFactoryImpl credentialsProviderFactory=new DefaultCredentialsProviderFactoryImpl();
  credentialsProviderFactory.setCaldavAdminUsername("username");
  credentialsProviderFactory.setCaldavAdminPassword("password");
  calendarDataDao.setCredentialsProviderFactory(credentialsProviderFactory);
  Resource problemResponse1=new ClassPathResource("caldav-examples/report-response-problem1.xml");
  HttpResponse response=mock(HttpResponse.class);
  HttpEntity entity=mock(HttpEntity.class);
  when(entity.getContent()).thenReturn(problemResponse1.getInputStream());
  StatusLine statusLine=mock(StatusLine.class);
  when(statusLine.getStatusCode()).thenReturn(207);
  when(response.getStatusLine()).thenReturn(statusLine);
  when(response.getEntity()).thenReturn(entity);
  HttpClient httpClient=mock(HttpClient.class);
  when(httpClient.execute((HttpHost)eq(null),isA(HttpRequest.class),isA(HttpContext.class))).thenReturn(response);
  calendarDataDao.setHttpClient(httpClient);
  Calendar calendar=calendarDataDao.getCalendar(calendarAccount,now,later);
  Assert.assertNotNull(calendar);
}
 

Example 48

From project SouthamptonUniversityMap, under directory /src/net/cbaines/suma/.

Source file: DataManager.java

  21 
vote

public static String getFileFromServer(String request) throws ClientProtocolException, IOException {
  StringBuilder builder=new StringBuilder();
  HttpClient client=new DefaultHttpClient();
  HttpGet httpGet=new HttpGet(request);
  HttpResponse response=client.execute(httpGet);
  StatusLine statusLine=response.getStatusLine();
  int statusCode=statusLine.getStatusCode();
  if (statusCode == 200) {
    HttpEntity entity=response.getEntity();
    InputStream content=entity.getContent();
    BufferedReader reader=new BufferedReader(new InputStreamReader(content));
    String line;
    while ((line=reader.readLine()) != null) {
      builder.append(line);
    }
  }
 else {
    Log.e("","Failed to download file");
  }
  return builder.toString();
}
 

Example 49

From project TextSecure, under directory /src/org/thoughtcrime/securesms/mms/.

Source file: MmsDownloadHelper.java

  21 
vote

private static byte[] makeRequest(MmsConnectionParameters connectionParameters,String url) throws ClientProtocolException, IOException {
  try {
    HttpClient client=constructHttpClient(connectionParameters);
    URI hostUrl=new URI(url);
    HttpHost target=new HttpHost(hostUrl.getHost(),hostUrl.getPort(),HttpHost.DEFAULT_SCHEME_NAME);
    HttpRequest request=new HttpGet(url);
    request.setParams(client.getParams());
    request.addHeader("Accept","*/*, application/vnd.wap.mms-message, application/vnd.wap.sic");
    HttpResponse response=client.execute(target,request);
    StatusLine status=response.getStatusLine();
    if (status.getStatusCode() != 200)     throw new IOException("Non-successful HTTP response: " + status.getReasonPhrase());
    return parseResponse(response.getEntity());
  }
 catch (  URISyntaxException use) {
    Log.w("MmsDownlader",use);
    throw new IOException("Bad URI syntax");
  }
}
 

Example 50

From project zaduiReader, under directory /src/org/mcsoxford/rss/.

Source file: RSSReader.java

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

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

Source file: HTTPRequestHelper.java

  19 
vote

/** 
 * Static utility method to create a default ResponseHandler that sends a Message to the passed in Handler with the response as a String, after the request completes.
 * @param handler
 * @return
 */
public static ResponseHandler<String> getResponseHandlerInstance(final Handler handler){
  final ResponseHandler<String> responseHandler=new ResponseHandler<String>(){
    public String handleResponse(    final HttpResponse response){
      Message message=handler.obtainMessage();
      Bundle bundle=new Bundle();
      StatusLine status=response.getStatusLine();
      Log.d(CLASSTAG," " + HTTPRequestHelper.CLASSTAG + " statusCode - "+ status.getStatusCode());
      Log.d(CLASSTAG," " + HTTPRequestHelper.CLASSTAG + " statusReasonPhrase - "+ status.getReasonPhrase());
      HttpEntity entity=response.getEntity();
      String result=null;
      if (entity != null) {
        try {
          result=HTTPRequestHelper.inputStreamToString(entity.getContent());
          bundle.putString("RESPONSE",result);
          message.setData(bundle);
          handler.sendMessage(message);
        }
 catch (        IOException e) {
          Log.e(CLASSTAG," " + HTTPRequestHelper.CLASSTAG,e);
          bundle.putString("RESPONSE","Error - " + e.getMessage());
          message.setData(bundle);
          handler.sendMessage(message);
        }
      }
 else {
        Log.w(CLASSTAG," " + HTTPRequestHelper.CLASSTAG + " empty response entity, HTTP error occurred");
        bundle.putString("RESPONSE","Error - " + response.getStatusLine().getReasonPhrase());
        message.setData(bundle);
        handler.sendMessage(message);
      }
      return result;
    }
  }
;
  return responseHandler;
}
 

Example 52

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

Source file: HttpURLClient.java

  19 
vote

public StatusLine getStatusLine(){
  try {
    return new BasicStatusLine(this.getProtocolVersion(),conn.getResponseCode(),conn.getResponseMessage());
  }
 catch (  IOException ex) {
    throw new RuntimeException("Error reading status line",ex);
  }
}
 

Example 53

From project leviathan, under directory /httpclient/src/test/java/ar/com/zauber/leviathan/impl/httpclient/.

Source file: HttpClientURIFetcherTest.java

  19 
vote

/** 
 * prueba el content type 
 */
@Test public final void testCharset() throws Exception {
  final HttpClient httpClient=mock(HttpClient.class);
  final URI uri=new URI("http://www.zaubersoftware.com");
  final InmutableURIAndCtx ctx=new InmutableURIAndCtx(uri);
  final StringEntity rta=new StringEntity(ESTA_ES_LA_RESPUESTA,"utf-8");
  final BasicHttpResponse httpResponse=new BasicHttpResponse(mock(StatusLine.class));
  httpResponse.setEntity(rta);
  when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(httpResponse);
  HTTPClientURIFetcher fetcher=new HTTPClientURIFetcher(httpClient);
  URIFetcherResponse ufr=fetcher.get(ctx);
  final Reader reader=ufr.getHttpResponse().getContent();
  final StringWriter output=new StringWriter();
  IOUtils.copy(reader,output);
  Assert.assertEquals(ESTA_ES_LA_RESPUESTA,output.toString());
}