Java Code Examples for org.apache.http.client.HttpClient

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

Example 1

From project 2Degrees-Toolbox, under directory /Toolbox/src/biz/shadowservices/DegreesToolbox/.

Source file: HttpGetter.java

  19 
vote

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

Example 2

From project ALP, under directory /workspace/alp-reporter/src/main/java/com/lohika/alp/reporter/client/.

Source file: LogUploader.java

  19 
vote

/** 
 * Upload certain log to server.
 * @param testMethodId the ID of test method which log will be uploaded 
 * @param logFile - instance of file to upload 
 * @throws ClientProtocolException the client protocol exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void upload(long testMethodId,File logFile) throws ClientProtocolException, IOException {
  String url=server + "/results/test-method/" + testMethodId+ "/log";
  HttpClient httpclient=new DefaultHttpClient();
  HttpPost httppost=new HttpPost(url);
  MultipartEntity mpEntity=new MultipartEntity();
  ContentBody cbFile=new FileBody(logFile);
  mpEntity.addPart("fileData",cbFile);
  httppost.setEntity(mpEntity);
  httpclient.execute(httppost);
}
 

Example 3

From project Airports, under directory /src/com/nadmm/airports/utils/.

Source file: NetworkUtils.java

  18 
vote

public static HttpClient getHttpClient(){
  SchemeRegistry registry=new SchemeRegistry();
  registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  HttpParams params=new BasicHttpParams();
  ClientConnectionManager cm=new ThreadSafeClientConnManager(params,registry);
  HttpClient client=new DefaultHttpClient(cm,params);
  return client;
}
 

Example 4

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

Source file: WebserviceTask.java

  18 
vote

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

Example 5

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

Source file: WebHelper.java

  18 
vote

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

Example 6

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

Source file: HttpClient4.java

  18 
vote

SingleClient(){
  HttpClient client=new DefaultHttpClient();
  ClientConnectionManager mgr=client.getConnectionManager();
  if (!(mgr instanceof ThreadSafeClientConnManager)) {
    HttpParams params=client.getParams();
    client=new DefaultHttpClient(new ThreadSafeClientConnManager(params,mgr.getSchemeRegistry()),params);
  }
  this.client=client;
}
 

Example 7

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

Source file: EasSyncService.java

  18 
vote

private HttpClient getHttpClient(int timeout){
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,CONNECTION_TIMEOUT);
  HttpConnectionParams.setSoTimeout(params,timeout);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpClient client=new DefaultHttpClient(getClientConnectionManager(),params);
  return client;
}
 

Example 8

From project androlog, under directory /androlog/src/main/java/de/akquinet/android/androlog/reporter/.

Source file: PostReporter.java

  18 
vote

public static void postReport(URL url,String param) throws IOException {
  HttpClient httpclient=new DefaultHttpClient();
  HttpPost httppost=new HttpPost(url.toExternalForm());
  try {
    List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("report",param));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    httpclient.execute(httppost);
  }
 catch (  ClientProtocolException e) {
    throw new IOException(e.getMessage());
  }
}
 

Example 9

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

Source file: SyncService.java

  18 
vote

@Override public void onCreate(){
  super.onCreate();
  final HttpClient httpClient=getHttpClient(this);
  final ContentResolver resolver=getContentResolver();
  mLocalExecutor=new LocalExecutor(getResources(),resolver);
  mRemoteExecutor=new RemoteExecutor(httpClient,resolver);
}
 

Example 10

From project Axon-trader, under directory /external-listeners/src/main/java/org/axonframework/samples/trader/listener/.

Source file: OrderbookExternalListener.java

  18 
vote

private void doHandle(TradeExecutedEvent event) throws IOException {
  String jsonObjectAsString=createJsonInString(event);
  HttpPost post=new HttpPost(remoteServerUri);
  post.setEntity(new StringEntity(jsonObjectAsString));
  post.addHeader("Content-Type","application/json");
  HttpClient client=new DefaultHttpClient();
  HttpResponse response=client.execute(post);
  if (response.getStatusLine().getStatusCode() != 200) {
    Writer writer=new StringWriter();
    IOUtils.copy(response.getEntity().getContent(),writer);
    logger.warn("Error while sending event to external system: {}",writer.toString());
  }
}
 

Example 11

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

Source file: SyncService.java

  18 
vote

@Override public void onCreate(){
  super.onCreate();
  final HttpClient httpClient=getHttpClient(this);
  final ContentResolver resolver=getContentResolver();
  mRemoteExecutor=new RemoteExecutor(httpClient,resolver);
}
 

Example 12

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

Source file: GoodreadsManager.java

  18 
vote

/** 
 * Create an HttpClient with specifically set buffer sizes to deal with potentially exorbitant settings on some HTC handsets.
 * @return
 */
private HttpClient newHttpClient(){
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,30000);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpConnectionParams.setLinger(params,0);
  HttpConnectionParams.setTcpNoDelay(params,false);
  HttpClient httpClient=new DefaultHttpClient(params);
  return httpClient;
}
 

Example 13

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

Source file: ServerProxyHandler.java

  18 
vote

public synchronized void shutdown(){
  if (client != null) {
    HttpClient tmp=client;
    client=null;
    ClientConnectionManager manager=tmp.getConnectionManager();
    if (manager != null)     manager.shutdown();
  }
}
 

Example 14

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

Source file: SyncService.java

  18 
vote

@Override public void onCreate(){
  super.onCreate();
  final HttpClient httpClient=getHttpClient(this);
  final ContentResolver resolver=getContentResolver();
  mLocalExecutor=new LocalExecutor(getResources(),resolver);
  mRemoteExecutor=new RemoteExecutor(httpClient,resolver);
}
 

Example 15

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

Source file: ConfigTest.java

  18 
vote

@Test public void testGetClient(){
  try {
    final Config config=new Config();
    HttpClient client=config.getClient();
    assertNotNull(client);
  }
 catch (  ConfigurationException ce) {
    fail("ConfigurationException shouldn't have been thrown." + ce.getMessage());
  }
catch (  MalformedURLException mue) {
    fail("MalformedURLException shouldn't have been thrown." + mue.getMessage());
  }
}
 

Example 16

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

Source file: HttpClientHttpChannelFactoryTest.java

  18 
vote

@Test public void crestConfigConstructorShouldUseHttpClientFactory() throws NoSuchFieldException, IllegalAccessException {
  HttpClient expected=mock(HttpClient.class);
  CRestConfig crestConfig=mock(CRestConfig.class);
  mockStatic(HttpClientFactory.class);
  when(HttpClientFactory.create(crestConfig,HttpClientHttpChannelFactory.class)).thenReturn(expected);
  HttpClientHttpChannelFactory toTest=new HttpClientHttpChannelFactory(crestConfig);
  assertSame(expected,Classes.getFieldValue(toTest,"client"));
}
 

Example 17

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

Source file: HTTPUtil.java

  18 
vote

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

Example 18

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

Source file: SyncService.java

  18 
vote

@Override public void onCreate(){
  super.onCreate();
  final HttpClient httpClient=getHttpClient(this);
  final ContentResolver resolver=getContentResolver();
  mLocalExecutor=new LocalExecutor(getResources(),resolver);
  mRemoteExecutor=new RemoteExecutor(httpClient,resolver);
}
 

Example 19

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

Source file: SyncService.java

  18 
vote

@Override public void onCreate(){
  super.onCreate();
  final HttpClient httpClient=getHttpClient(this);
  final ContentResolver resolver=getContentResolver();
  mLocalExecutor=new LocalExecutor(getResources(),resolver);
  mRemoteExecutor=new RemoteExecutor(httpClient,resolver);
}
 

Example 20

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

Source file: HttpClientFactory.java

  18 
vote

public static HttpClient getThreadSafeClient(){
  HttpParams params=new BasicHttpParams();
  ConnManagerParams.setMaxTotalConnections(params,100);
  HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
  HttpConnectionParams.setConnectionTimeout(params,REGISTRATION_TIMEOUT);
  HttpConnectionParams.setSoTimeout(params,REGISTRATION_TIMEOUT);
  ConnManagerParams.setTimeout(params,REGISTRATION_TIMEOUT);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  ClientConnectionManager mgr=new ThreadSafeClientConnManager(params,schemeRegistry);
  HttpClient client=new DefaultHttpClient(mgr,params);
  return client;
}
 

Example 21

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

Source file: RestService.java

  18 
vote

@Override public void onCreate(){
  super.onCreate();
  final HttpClient httpClient=HttpHelper.getHttpClient(this);
  final ContentResolver resolver=getContentResolver();
  mLocalExecutor=new LocalJsonExecutor(getResources(),resolver);
  mRemoteExecutor=new RemoteJsonExecutor(httpClient,resolver);
  mApplicationContext=getApplicationContext();
}
 

Example 22

From project flazr, under directory /src/main/java/com/flazr/util/.

Source file: Utils.java

  18 
vote

public static String getOverHttp(String url){
  HttpClient client=new DefaultHttpClient();
  HttpGet method=new HttpGet(url);
  String result=null;
  try {
    HttpResponse response=client.execute(method);
    result=EntityUtils.toString(response.getEntity());
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return result;
}
 

Example 23

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

Source file: SyncService.java

  18 
vote

@Override public void onCreate(){
  super.onCreate();
  final HttpClient httpClient=getHttpClient(this);
  final ContentResolver resolver=getContentResolver();
  mLocalExecutor=new LocalExecutor(getResources(),resolver);
  mRemoteExecutor=new RemoteExecutor(httpClient,resolver);
}
 

Example 24

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

Source file: TaskManager.java

  18 
vote

private static HttpEntity sendRequest(String url) throws Exception {
  HttpClient client=new DefaultHttpClient();
  HttpUriRequest request=new HttpGet(SERVER_URL + url);
  HttpResponse response=client.execute(request);
  return response.getEntity();
}
 

Example 25

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

Source file: TimeTableAPI.java

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

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

Source file: SolrClient.java

  17 
vote

static public void reindex(){
  HttpClient client=new DefaultHttpClient();
  HtmlCleaner cleaner=new HtmlCleaner();
  HttpGet get;
  HttpResponse response;
  String httpQuery="";
  try {
    httpQuery=ApplicationProperties.getProperty("solr.server.address") + ApplicationProperties.getProperty("solr.core.path") + ApplicationProperties.getProperty("solr.query.command.reindex");
    get=new HttpGet(httpQuery);
    response=client.execute(get);
    cleaner.clean(new InputStreamReader(response.getEntity().getContent()));
  }
 catch (  Exception ex) {
    logger.error(httpQuery);
    logger.error(ex.getMessage(),ex);
  }
}
 

Example 27

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

Source file: YahooQuoteService.java

  17 
vote

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

Example 28

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

Source file: Http.java

  17 
vote

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

Example 29

From project Alerte-voirie-android, under directory /src/com/fabernovel/alertevoirie/webservice/.

Source file: AVService.java

  17 
vote

@Override protected HttpResponse[] doInBackground(ArrayList<Object>... params){
  HttpResponse[] response=new HttpResponse[2];
  int i=0;
  for (  ArrayList<Object> PicArray : params) {
    if (PicArray != null) {
      HttpClient httpClient=new DefaultHttpClient();
      HttpContext localContext=new BasicHttpContext();
      HttpPost httpPost=new HttpPost((String)PicArray.get(0));
      httpPost.addHeader("udid",(String)PicArray.get(1));
      Log.d(Constants.PROJECT_TAG,"length : " + ((String)PicArray.get(2)).length());
      httpPost.addHeader("img_comment",(String)PicArray.get(2));
      httpPost.addHeader("incident_id",(String)PicArray.get(3));
      httpPost.addHeader("type",(String)PicArray.get(4));
      if (((Boolean)PicArray.get(6)).booleanValue()) {
        httpPost.addHeader("INCIDENT_CREATION","true");
      }
      try {
        FileEntity file=new FileEntity((File)PicArray.get(5),"image/jpeg");
        file.setContentType("image/jpeg");
        httpPost.setEntity(file);
        response[i++]=httpClient.execute(httpPost,localContext);
      }
 catch (      IOException e) {
        Log.e(Constants.PROJECT_TAG,"IOException postImage",e);
      }
catch (      IllegalStateException e) {
        Log.e(Constants.PROJECT_TAG,"IllegalStateException postImage",e);
      }
    }
  }
  return response;
}
 

Example 30

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

Source file: Chalmrest.java

  17 
vote

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

Example 31

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

Source file: WebClient.java

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

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

Source file: RadioInfo.java

  17 
vote

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

Example 33

From project android_packages_apps_Gallery2, under directory /gallerycommon/src/com/android/gallery3d/common/.

Source file: HttpClientFactory.java

  17 
vote

/** 
 * Creates an HttpClient with the specified userAgent string.
 * @param userAgent the userAgent string
 * @return the client
 */
public static HttpClient newHttpClient(String userAgent){
  try {
    Class<?> clazz=Class.forName("android.net.http.AndroidHttpClient");
    Method newInstance=clazz.getMethod("newInstance",String.class);
    Object instance=newInstance.invoke(null,userAgent);
    HttpClient client=(HttpClient)instance;
    HttpParams params=client.getParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);
    ConnManagerParams.setTimeout(params,60 * 1000);
    return client;
  }
 catch (  InvocationTargetException e) {
    throw new RuntimeException(e);
  }
catch (  ClassNotFoundException e) {
    throw new RuntimeException(e);
  }
catch (  NoSuchMethodException e) {
    throw new RuntimeException(e);
  }
catch (  IllegalAccessException e) {
    throw new RuntimeException(e);
  }
}
 

Example 34

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

Source file: VeecheckThread.java

  17 
vote

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

Example 35

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

Source file: ModuleUtils.java

  17 
vote

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

Example 36

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

Source file: FileApiClientAdapterImpl.java

  17 
vote

private StringResponse executeHttpcall(HttpRequestBase httpRequest) throws FileApiException {
  HttpClient httpClient=null;
  try {
    httpClient=new DefaultHttpClient();
    setupProxy(httpClient);
    HttpResponse response=httpClient.execute(httpRequest);
    if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK)     return inputStreamToString(response.getEntity().getContent(),null);
    throw new FileApiException(inputStreamToString(response.getEntity().getContent(),null).getContents());
  }
 catch (  IOException e) {
    throw new FileApiException(e);
  }
 finally {
    if (null != httpClient)     httpClient.getConnectionManager().shutdown();
  }
}
 

Example 37

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

Source file: ImageManager.java

  17 
vote

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

Example 38

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

Source file: LatkeClient.java

  17 
vote

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

Example 39

From project basiclti-portlet, under directory /src/main/java/au/edu/anu/portal/portlets/basiclti/support/.

Source file: HttpSupport.java

  17 
vote

/** 
 * Make a POST request with the given Map of parameters to be encoded
 * @param address	address to POST to
 * @param params	Map of params to use as the form parameters
 * @return
 */
public static String doPost(String address,Map<String,String> params){
  HttpClient httpclient=new DefaultHttpClient();
  try {
    HttpPost httppost=new HttpPost(address);
    List<NameValuePair> formparams=new ArrayList<NameValuePair>();
    for (    Map.Entry<String,String> entry : params.entrySet()) {
      formparams.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
    }
    UrlEncodedFormEntity entity=new UrlEncodedFormEntity(formparams,HTTP.UTF_8);
    httppost.setEntity(entity);
    HttpResponse response=httpclient.execute(httppost);
    String responseContent=EntityUtils.toString(response.getEntity());
    return responseContent;
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
 finally {
    httpclient.getConnectionManager().shutdown();
  }
  return null;
}
 

Example 40

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

Source file: JoinServiceBase.java

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

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

Source file: LoaderImageView.java

  17 
vote

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

Example 42

From project bookmarktodesktop-android-application, under directory /src/be/vbsteven/bmtodesk/.

Source file: BackgroundSharingService.java

  17 
vote

/** 
 * sends the bookmark to the server in a POST request
 * @param title
 * @param url
 */
private void sendToServer(final String title,final String url){
  showProgress();
  String username=Global.getUsername(BackgroundSharingService.this);
  String password=Global.getPassword(BackgroundSharingService.this);
  String responseMessage;
  try {
    HttpClient httpclient=new DefaultHttpClient();
    HttpPost post=new HttpPost(URI.create(URL));
    ArrayList<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(4);
    nameValuePairs.add(new BasicNameValuePair("username",username));
    nameValuePairs.add(new BasicNameValuePair("password",password));
    nameValuePairs.add(new BasicNameValuePair("title",title));
    nameValuePairs.add(new BasicNameValuePair("url",url));
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response=httpclient.execute(post);
    BufferedReader reader=new BufferedReader(new InputStreamReader(response.getEntity().getContent(),"UTF-8"));
    responseMessage=reader.readLine();
  }
 catch (  Exception e) {
    responseMessage="REQUESTFAILED";
  }
  hideProgress();
  onResult(responseMessage);
}
 

Example 43

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

Source file: OAuth2Request.java

  17 
vote

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

Example 44

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

Source file: RadioInfo.java

  17 
vote

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

Example 45

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

Source file: ConexionSii.java

  17 
vote

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

Example 46

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

Source file: OAuthGoogle.java

  17 
vote

@Override public void onClick(View v){
  final SharedPreferences settings=v.getContext().getSharedPreferences(PREF_NAME,0);
  String accessToken=settings.getString(PREF_TOKENS[authenticator],"");
  TextView textView=(TextView)findViewById(R.id.google_contacts);
  try {
    Uri.Builder builder=new Uri.Builder().scheme("http").authority("musulogin.appspot.com").path("oauth2users").appendQueryParameter("token",accessToken);
    Log.i(TAG,builder.toString());
    HttpClient client=new DefaultHttpClient();
    HttpGet request=new HttpGet(builder.toString());
    HttpResponse response=client.execute(request);
    BufferedReader rd=new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line="";
    String jsonStr="";
    while ((line=rd.readLine()) != null) {
      jsonStr+=line;
    }
    JSONObject object=new JSONObject(jsonStr);
    String keysStr=object.getString("keys");
    JSONArray keys=new JSONArray(keysStr);
    textView.setText("");
    friendList=new ArrayList<Pair<String,String>>(keys.length());
    for (int i=0; i < keys.length(); i++) {
      JSONObject friend=keys.getJSONObject(i);
      textView.append(friend.getString("key") + "->" + friend.getString("uid")+ "\n");
      friendList.add(new Pair<String,String>(friend.getString("uid"),friend.getString("key")));
    }
    showDialog(DIALOG_CHOOSE_FRIEND_TO_ADD);
  }
 catch (  Exception e) {
    Log.e(TAG,e.toString());
  }
}
 

Example 47

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

Source file: ReadDataAsyncTask.java

  17 
vote

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

Example 48

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

Source file: HttpConnector.java

  17 
vote

private Runnable createSendAction(final String httpBase,final String xml,final ConnectorCallback callback){
  return new Runnable(){
    @Override public void run(){
      final String id=HttpConnectorID.getNext();
      debug("Connector [{0}] send: {1}",id,xml);
      final HttpClient client=new DefaultHttpClient();
      int status=0;
      String responseString=null;
      final HttpPost post=new HttpPost(httpBase);
      try {
        post.setEntity(new StringEntity(xml,"utf-8"));
        System.out.println("SENDING: " + xml);
        final HttpResponse response=client.execute(post);
        responseString=EntityUtils.toString(response.getEntity());
      }
 catch (      final Exception e) {
        callback.onResponseError(xml,e);
        e.printStackTrace();
      }
      try {
        post.setEntity(new StringEntity(xml,"text/xml"));
        System.out.println("SENDING: " + xml);
        HttpResponse response=client.execute(post);
        responseString=EntityUtils.toString(response.getEntity());
        status=response.getStatusLine().getStatusCode();
      }
 catch (      final Exception e) {
        callback.onResponseError(xml,e);
        e.printStackTrace();
      }
      receiveService.execute(createResponseAction(xml,callback,id,status,responseString));
    }
  }
;
}
 

Example 49

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

Source file: AndroidUrlDownloader.java

  17 
vote

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

Example 50

From project eve-api, under directory /cdi/src/main/java/org/onsteroids/eve/api/provider/img/.

Source file: DefaultCharacterPortraitApi.java

  17 
vote

@Override public CharacterPortrait getCharacterPortrait(long characterId,PortraitSize size) throws ApiException {
  HttpClient httpClient=httpClientProvider.get();
  List<NameValuePair> qparams=Lists.newArrayList();
  qparams.add(new BasicNameValuePair("c",Long.toString(characterId)));
  qparams.add(new BasicNameValuePair("s",Integer.toString(size.getSize())));
  final URI requestURI;
  try {
    requestURI=URIUtils.createURI(serverUri.getScheme(),serverUri.getHost(),serverUri.getPort(),serverUri.getPath(),URLEncodedUtils.format(qparams,"UTF-8"),null);
  }
 catch (  URISyntaxException e) {
    throw new InternalApiException(e);
  }
  LOG.trace("Resulting URI: {}",requestURI);
  final HttpPost postRequest=new HttpPost(requestURI);
  LOG.trace("Fetching result from {}...",serverUri);
  final HttpResponse response;
  try {
    response=httpClient.execute(postRequest);
  }
 catch (  IOException e) {
    throw new InternalApiException(e);
  }
  if (!FORMAT.equals(response.getEntity().getContentType().getValue())) {
    throw new InternalApiException("Failed to fetch portrait [" + response.getEntity().getContentType().getValue() + "].");
  }
  try {
    return new DefaultCharacterPortrait(response);
  }
 catch (  IOException e) {
    throw new InternalApiException(e);
  }
}
 

Example 51

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

Source file: AddAccount.java

  17 
vote

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

Example 52

From project fanfoudroid, under directory /src/eriji/com/oauth/.

Source file: XAuthClient.java

  17 
vote

public void retrieveAccessToken(String username,String password) throws OAuthStoreException, ClientProtocolException, IOException, ResponseException {
  HttpClient client=new DefaultHttpClient();
  HttpPost request=new HttpPost(BASE_URL + "/access_token");
  CommonsHttpOAuthConsumer consumer=new CommonsHttpOAuthConsumer(CONSUMER_KEY,CONSUMER_SECRET);
  List<BasicNameValuePair> params=Arrays.asList(new BasicNameValuePair("x_auth_username",username),new BasicNameValuePair("x_auth_password",password),new BasicNameValuePair("x_auth_mode","client_auth"));
  UrlEncodedFormEntity entity=null;
  try {
    entity=new UrlEncodedFormEntity(params,HTTP.UTF_8);
  }
 catch (  UnsupportedEncodingException e) {
    throw new RuntimeException("wtf");
  }
  request.setEntity(entity);
  try {
    consumer.sign(request);
  }
 catch (  OAuthMessageSignerException e) {
    e.printStackTrace();
  }
catch (  OAuthExpectationFailedException e) {
    e.printStackTrace();
  }
catch (  OAuthCommunicationException e) {
    e.printStackTrace();
  }
  HttpResponse response=client.execute(request);
  String responseString=Response.entityToString(response.getEntity());
  String[] tmp=TextUtils.split(responseString,"&");
  if (tmp.length < 2) {
    Log.e(TAG,"something wrong with access token response: " + responseString);
    return;
  }
  String token=tmp[0].replace("oauth_token=","");
  String tokenSerect=tmp[1].replace("oauth_token_secret=","");
  mAccessToken=new OAuthAccessToken(token,tokenSerect);
  storeAccessToken();
  logger.info("retrieve access token with request token " + mConsumer.getToken() + " "+ mAccessToken+ " "+ mProvider.getAccessTokenEndpointUrl());
}
 

Example 53

From project fed4j, under directory /src/main/java/com/jute/fed4j/engine/component/http/.

Source file: HttpDispatcherImpl_Jakarta.java

  17 
vote

public void run(HttpComponent component){
  this.commponent=component;
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,component.connectTimeout);
  HttpConnectionParams.setSoTimeout(params,component.readTimeout);
  try {
    this.init(component);
    HttpClient httpclient=new MyHttpClient(getConnectionManager(params,component.enablePersistentConnection),params);
    if (component.enableProxy && "http".equals(component.proxyType)) {
      HttpHost proxy=new HttpHost(component.proxyHost,component.proxyPort,component.proxyType);
      httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
    }
    HttpUriRequest request=new HttpRequest(component.method,component.uri);
    MyHttpResponseHandler responseHandler=new MyHttpResponseHandler(component.responseCharset);
    String body=httpclient.execute(request,responseHandler);
    this.onResponse(component,responseHandler.code,body);
  }
 catch (  SocketTimeoutException e) {
    onException(component,-2," socket timeout error occurs: " + e.getMessage());
  }
catch (  ClientProtocolException e) {
    onException(component,-3," error resposed from server: " + e.getMessage());
  }
catch (  IOException e) {
    onException(component,-4," error occurs during dispatch: " + e.getMessage());
  }
catch (  Exception e) {
    onException(component,-5,"error occurs during parsing xml:" + e.getMessage());
  }
}
 

Example 54

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

Source file: PhotoActivity.java

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

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

Source file: GReader.java

  17 
vote

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

Example 56

From project Flume-Hive, under directory /src/java/com/cloudera/flume/handlers/hive/.

Source file: MarkerStore.java

  17 
vote

public boolean sendESQuery(String elasticSearchUrl,String sb){
  boolean success=true;
  LOG.info("sending batched stringentities");
  LOG.info("elasticSearchUrl: " + elasticSearchUrl);
  try {
    HttpClient httpClient=new DefaultHttpClient();
    HttpPost httpPost=new HttpPost(elasticSearchUrl);
    StringEntity se=new StringEntity(sb);
    httpPost.setEntity(se);
    HttpResponse hr=httpClient.execute(httpPost);
    LOG.info("HTTP Response: " + hr.getStatusLine());
    LOG.info("Closing httpConnection");
    httpClient.getConnectionManager().shutdown();
    LOG.info("booooooo: " + CharStreams.toString(new InputStreamReader(se.getContent())));
  }
 catch (  IOException e) {
    e.printStackTrace();
    success=false;
  }
 finally {
    if (!success) {
      LOG.info("ESQuery wasn't successful, writing to markerfolder");
      writeElasticSearchToMarkerFolder(new StringBuilder(sb));
    }
  }
  LOG.info("ESQuery was successful, yay!");
  return success;
}
 

Example 57

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

Source file: ClientAbortMethod.java

  17 
vote

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

Example 58

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

Source file: LeonardoUpload.java

  17 
vote

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

Example 59

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

Source file: AndroidNet.java

  17 
vote

private void doHttp(final boolean isPost,final String url,final String data,final Callback<String> callback){
  new Thread("AndroidNet.doHttp"){
    public void run(){
      HttpClient httpclient=new DefaultHttpClient();
      HttpRequestBase req=null;
      if (isPost) {
        HttpPost httppost=new HttpPost(url);
        if (data != null) {
          try {
            httppost.setEntity(new StringEntity(data));
          }
 catch (          UnsupportedEncodingException e) {
            notifyFailure(callback,e);
          }
        }
        req=httppost;
      }
 else {
        req=new HttpGet(url);
      }
      try {
        HttpResponse response=httpclient.execute(req);
        notifySuccess(callback,EntityUtils.toString(response.getEntity()));
      }
 catch (      Exception e) {
        notifyFailure(callback,e);
      }
    }
  }
.start();
}
 

Example 60

From project graylog2-server, under directory /src/main/java/org/graylog2/systeminformation/.

Source file: Sender.java

  17 
vote

public static void send(Map<String,Object> info,Core server){
  HttpClient httpClient=new DefaultHttpClient();
  try {
    HttpPost request=new HttpPost(getTarget(server));
    List<NameValuePair> nameValuePairs=Lists.newArrayList();
    nameValuePairs.add(new BasicNameValuePair("systeminfo",JSONValue.toJSONString(info)));
    request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response=httpClient.execute(request);
    if (response.getStatusLine().getStatusCode() != 201) {
      LOG.warn("Response code for system statistics was not 201, but " + response.getStatusLine().getStatusCode());
    }
  }
 catch (  Exception e) {
    LOG.warn("Could not send system statistics.",e);
  }
 finally {
    httpClient.getConnectionManager().shutdown();
  }
}
 

Example 61

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

Source file: SimpleWikiHelper.java

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

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

Source file: onlineService2Provider.java

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

From project httpClient, under directory /httpclient/src/examples/org/apache/http/examples/client/.

Source file: ClientAbortMethod.java

  17 
vote

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

Example 64

From project ihatovgram, under directory /src/client/android/ihatovgram/lib/httpcomponents-client-4.1.3/examples/org/apache/http/examples/client/.

Source file: ClientAbortMethod.java

  17 
vote

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

Example 65

From project 4308Cirrus, under directory /tendril-android-lib/src/main/java/edu/colorado/cs/cirrus/android/.

Source file: HttpUtils.java

  15 
vote

public static HttpClient getNewHttpClient(){
  try {
    KeyStore trustStore=KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null,null);
    SSLSocketFactory sf=new EasySSLSocketFactory(trustStore);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    HttpParams params=new BasicHttpParams();
    HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params,HTTP.UTF_8);
    SchemeRegistry registry=new SchemeRegistry();
    registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
    registry.register(new Scheme("https",sf,443));
    ClientConnectionManager ccm=new ThreadSafeClientConnManager(params,registry);
    return new DefaultHttpClient(ccm,params);
  }
 catch (  Exception e) {
    return new DefaultHttpClient();
  }
}
 

Example 66

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

Source file: AirCastingModule.java

  15 
vote

@Override protected void configure(){
  requestStaticInjection(HttpBuilder.class);
  bind(Gson.class).toProvider(GsonProvider.class).in(Scopes.SINGLETON);
  bind(HttpClient.class).to(DefaultHttpClient.class);
  bind(AirCastingDB.class).toProvider(AirCastingDBProvider.class);
  bind(NoteOverlay.class).toProvider(NoteOverlayProvider.class);
  bind(Geocoder.class).toProvider(GeocoderProvider.class);
  bind(EventBus.class).in(Scopes.SINGLETON);
  bindConstant().annotatedWith(SharedPreferencesName.class).to("pl.llp.aircasting_preferences");
  bind(BluetoothAdapter.class).toProvider(BluetoothAdapterProvider.class);
  bind(TelephonyManager.class).toProvider(new SystemServiceProvider<TelephonyManager>(Context.TELEPHONY_SERVICE));
}
 

Example 67

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

Source file: CatchAPI.java

  15 
vote

private HttpClient getHttpClientNoToken(){
  if (httpClientNoToken == null) {
    HttpParams params=new BasicHttpParams();
    HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(params,userAgent);
    HttpProtocolParams.setContentCharset(params,"UTF-8");
    httpClientNoToken=new DefaultHttpClient(params);
  }
  return httpClientNoToken;
}
 

Example 68

From project android-rackspacecloud, under directory /extensions/apachehc/src/main/java/org/jclouds/http/apachehc/config/.

Source file: ApacheHCHttpCommandExecutorServiceModule.java

  15 
vote

@Provides @Singleton HttpClient newDefaultHttpClient(HttpUtils utils,BasicHttpParams params,ClientConnectionManager cm){
  DefaultHttpClient client=new DefaultHttpClient(cm,params);
  if (utils.useSystemProxies()) {
    ProxySelectorRoutePlanner routePlanner=new ProxySelectorRoutePlanner(client.getConnectionManager().getSchemeRegistry(),ProxySelector.getDefault());
    client.setRoutePlanner(routePlanner);
  }
  return client;
}
 

Example 69

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

Source file: ConnectionBasicAuth.java

  15 
vote

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

Example 70

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

Source file: ConnectionBasicAuth.java

  15 
vote

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

Example 71

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

Source file: DefaultRequestMethod.java

  15 
vote

public void init(IEntity destEntity,HttpRequestBase method,HttpClient connector,IConfiguration config,IConfiguration.ContentFormat format){
  this.connector=connector;
  this.method=method;
  this.destEntity=destEntity;
  this.configuration=config;
  this.format=format;
}
 

Example 72

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

Source file: NetTest.java

  15 
vote

public static HttpClient wrapClient(HttpClient base){
  try {
    SSLContext ctx=SSLContext.getInstance("TLS");
    X509TrustManager tm=new X509TrustManager(){
      @Override public void checkClientTrusted(      X509Certificate[] xcs,      String string) throws CertificateException {
      }
      @Override public void checkServerTrusted(      X509Certificate[] xcs,      String string) throws CertificateException {
      }
      @Override public X509Certificate[] getAcceptedIssuers(){
        return null;
      }
    }
;
    ctx.init(null,new TrustManager[]{tm},null);
    SSLSocketFactory ssf=new SSLSocketFactory(ctx);
    ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm=base.getConnectionManager();
    SchemeRegistry sr=ccm.getSchemeRegistry();
    sr.register(new Scheme("https",ssf,443));
    return new DefaultHttpClient(ccm,base.getParams());
  }
 catch (  Exception ex) {
    throw new RuntimeException(ex);
  }
}
 

Example 73

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

Source file: DefaultC2dmManagerTest.java

  15 
vote

@Before public void setup() throws ClientProtocolException, IOException {
  message=new MessageBuilder().collapseKey("collapsekey").registrationId("myregistrationid").put("mykey","mydata").build();
  factory=new TestableAuthTokenProvider(AUTH_TOKEN);
  client=mock(HttpClient.class);
  cut=new DefaultC2dmManager(client,factory);
}
 

Example 74

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

Source file: JBossURLFetchService.java

  15 
vote

protected HttpClient getClient(){
  if (client == null) {
    SchemeRegistry schemeRegistry=new SchemeRegistry();
    schemeRegistry.register(new Scheme("http",80,PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https",443,SSLSocketFactory.getSocketFactory()));
    HttpParams params=new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params,30 * 1000);
    HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params,"UTF-8");
    ClientConnectionManager ccm=new ThreadSafeClientConnManager(schemeRegistry);
    client=new DefaultHttpClient(ccm,params);
  }
  return client;
}
 

Example 75

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

Source file: CineShowtimeFactory.java

  15 
vote

private HttpClient getClient(){
  if (client == null) {
    client=new DefaultHttpClient();
  }
  return client;
}
 

Example 76

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

Source file: HTTPRequestHelper.java

  15 
vote

/** 
 * Once the client and method are established, execute the request. 
 * @param client
 * @param method
 */
private void execute(HttpClient client,HttpRequestBase method){
  Log.d(CLASSTAG," " + HTTPRequestHelper.CLASSTAG + " execute invoked");
  BasicHttpResponse errorResponse=new BasicHttpResponse(new ProtocolVersion("HTTP_ERROR",1,1),500,"ERROR");
  try {
    client.execute(method,this.responseHandler);
    Log.d(CLASSTAG," " + HTTPRequestHelper.CLASSTAG + " request completed");
  }
 catch (  Exception e) {
    Log.e(CLASSTAG," " + HTTPRequestHelper.CLASSTAG,e);
    errorResponse.setReasonPhrase(e.getMessage());
    try {
      this.responseHandler.handleResponse(errorResponse);
    }
 catch (    Exception ex) {
      Log.e(CLASSTAG," " + HTTPRequestHelper.CLASSTAG,ex);
    }
  }
}
 

Example 77

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

Source file: MartServiceClientImpl.java

  15 
vote

public MartServiceClientImpl(HttpClient httpClient,String martUrl,String databaseName,String datasetName){
  this.martUri=URI.create(martUrl);
  this.databaseName=databaseName;
  this.datasetName=datasetName;
  this.httpClient=httpClient;
}
 

Example 78

From project httpcache4j, under directory /resolvers/resolvers-httpcomponents-httpclient/src/main/java/org/codehaus/httpcache4j/resolver/.

Source file: HTTPClientResponseResolver.java

  15 
vote

public HTTPClientResponseResolver(HttpClient httpClient,ResolverConfiguration configuration){
  super(configuration);
  this.httpClient=httpClient;
  HTTPHost proxyHost=getProxyAuthenticator().getConfiguration().getHost();
  HttpParams params=httpClient.getParams();
  if (params == null) {
    params=new BasicHttpParams();
    if (httpClient instanceof DefaultHttpClient) {
      ((DefaultHttpClient)httpClient).setParams(params);
    }
  }
  if (proxyHost != null) {
    HttpHost host=new HttpHost(proxyHost.getHost(),proxyHost.getPort(),proxyHost.getScheme());
    params.setParameter(ConnRoutePNames.DEFAULT_PROXY,host);
  }
  params.setParameter(CoreProtocolPNames.USER_AGENT,getConfiguration().getUserAgent());
}