Java Code Examples for org.apache.http.protocol.BasicHttpContext

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 dreamDroid, under directory /src/net/reichholf/dreamdroid/helpers/.

Source file: SimpleHttpClient.java

  23 
vote

/** 
 * @param sp SharedPreferences of the Base-Context
 */
public SimpleHttpClient(){
  BasicHttpParams params=new BasicHttpParams();
  params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,10000);
  mDhc=new DefaultHttpClient(getEasySSLClientConnectionManager(),params);
  mContext=new BasicHttpContext();
  applyConfig();
}
 

Example 2

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

Source file: HttpClient.java

  21 
vote

private void setBasicAuth(){
  BasicScheme basicScheme=new BasicScheme();
  mAuthScope=new AuthScope(SERVER_HOST,AuthScope.ANY_PORT);
  mClient.setCredentialsProvider(new BasicCredentialsProvider());
  localcontext=new BasicHttpContext();
  localcontext.setAttribute("preemptive-auth",basicScheme);
  mClient.addRequestInterceptor(preemptiveAuth,0);
}
 

Example 3

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

Source file: ClientMultiThreadedExecution.java

  21 
vote

public GetThread(HttpClient httpClient,HttpGet httpget,int id){
  this.httpClient=httpClient;
  this.context=new BasicHttpContext();
  this.httpget=httpget;
  this.id=id;
}
 

Example 4

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

Source file: ClientPreemptiveBasicAuthentication.java

  21 
vote

public static void main(String[] args) throws Exception {
  HttpHost targetHost=new HttpHost("localhost",80,"http");
  DefaultHttpClient httpclient=new DefaultHttpClient();
  try {
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(targetHost.getHostName(),targetHost.getPort()),new UsernamePasswordCredentials("username","password"));
    AuthCache authCache=new BasicAuthCache();
    BasicScheme basicAuth=new BasicScheme();
    authCache.put(targetHost,basicAuth);
    BasicHttpContext localcontext=new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE,authCache);
    HttpGet httpget=new HttpGet("/");
    System.out.println("executing request: " + httpget.getRequestLine());
    System.out.println("to target: " + targetHost);
    for (int i=0; i < 3; i++) {
      HttpResponse response=httpclient.execute(targetHost,httpget,localcontext);
      HttpEntity entity=response.getEntity();
      System.out.println("----------------------------------------");
      System.out.println(response.getStatusLine());
      if (entity != null) {
        System.out.println("Response content length: " + entity.getContentLength());
      }
      EntityUtils.consume(entity);
    }
  }
  finally {
    httpclient.getConnectionManager().shutdown();
  }
}
 

Example 5

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

Source file: WebService.java

  21 
vote

public WebService(String serviceName){
  HttpParams myParams=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(myParams,20000);
  HttpConnectionParams.setSoTimeout(myParams,20000);
  httpClient=new DefaultHttpClient(myParams);
  localContext=new BasicHttpContext();
  webServiceUrl=serviceName;
}
 

Example 6

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

Source file: WebService.java

  21 
vote

public WebService(){
  HttpParams myParams=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(myParams,20000);
  HttpConnectionParams.setSoTimeout(myParams,20000);
  httpClient=new DefaultHttpClient(myParams);
  localContext=new BasicHttpContext();
}
 

Example 7

From project gmarks-android, under directory /src/main/java/org/thomnichols/android/gmarks/.

Source file: BookmarksQueryService.java

  21 
vote

private BookmarksQueryService(String userAgent){
  ctx=new BasicHttpContext();
  cookieStore=new BasicCookieStore();
  ctx.setAttribute(ClientContext.COOKIE_STORE,cookieStore);
  String defaultUA="Mozilla/5.0 (Linux; U; Android 2.1; en-us) AppleWebKit/522+ (KHTML, like Gecko) Safari/419.3";
  http=AndroidHttpClient.newInstance(userAgent != null ? userAgent : defaultUA);
}
 

Example 8

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

Source file: Executor.java

  21 
vote

Executor(final HttpClient httpclient){
  super();
  this.httpclient=httpclient;
  this.localContext=new BasicHttpContext();
  this.authCache=new BasicAuthCache();
}
 

Example 9

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

Source file: ClientMultiThreadedExecution.java

  21 
vote

public GetThread(HttpClient httpClient,HttpGet httpget,int id){
  this.httpClient=httpClient;
  this.context=new BasicHttpContext();
  this.httpget=httpget;
  this.id=id;
}
 

Example 10

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

Source file: AVService.java

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

From project android-bankdroid, under directory /src/eu/nullbyte/android/urllib/.

Source file: Urllib.java

  20 
vote

public Urllib(boolean acceptInvalidCertificates,boolean allowCircularRedirects){
  this.acceptInvalidCertificates=acceptInvalidCertificates;
  this.headers=new HashMap<String,String>();
  HttpParams params=new BasicHttpParams();
  HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setContentCharset(params,this.charset);
  params.setBooleanParameter("http.protocol.expect-continue",false);
  if (allowCircularRedirects)   params.setBooleanParameter("http.protocol.allow-circular-redirects",true);
  if (acceptInvalidCertificates) {
    SchemeRegistry registry=new SchemeRegistry();
    registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
    registry.register(new Scheme("https",new EasySSLSocketFactory(),443));
    ClientConnectionManager manager=new ThreadSafeClientConnManager(params,registry);
    httpclient=new DefaultHttpClient(manager,params);
  }
 else {
    SchemeRegistry registry=new SchemeRegistry();
    registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
    registry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
    ClientConnectionManager manager=new ThreadSafeClientConnManager(params,registry);
    httpclient=new DefaultHttpClient(manager,params);
  }
  context=new BasicHttpContext();
}
 

Example 12

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

Source file: JoinServiceBase.java

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

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

Source file: Authentication.java

  20 
vote

/** 
 * Example of the use of cookies: http://www.java-tips.org/other-api-tips/httpclient/how-to-use-http-cookies.html
 * @param username
 * @param password
 * @return
 * @throws HttpException
 * @throws IOException
 */
private boolean authenticate(String username,String password) throws HttpException, IOException {
  List<NameValuePair> formparams=new ArrayList<NameValuePair>();
  formparams.add(new BasicNameValuePair("login",username));
  formparams.add(new BasicNameValuePair("password",password));
  UrlEncodedFormEntity entity=new UrlEncodedFormEntity(formparams,"UTF-8");
  HttpPost method=new HttpPost(server + "/session");
  method.setEntity(entity);
  HttpContext localContext=new BasicHttpContext();
  HttpResponse response=client.execute(method,localContext);
  if (response.getStatusLine().getStatusCode() != 302) {
    log.error("Invalid response code " + response.getStatusLine().getStatusCode());
    return false;
  }
  if (!response.containsHeader("Location") || !response.getFirstHeader("Location").getValue().equals(server + "/home")) {
    log.error("Invalid password");
    return false;
  }
  if (!response.containsHeader("Set-Cookie")) {
    log.error("The response doesn't have an authenticated cookie");
    return false;
  }
  cookie=response.getFirstHeader("Set-Cookie").getValue();
  log.info("Authenticated on " + server);
  return true;
}
 

Example 14

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

Source file: PreemptiveHttpClient.java

  20 
vote

private DefaultHttpClient createHttpClient(String userName,String password,int timeout){
  BasicHttpParams params=new BasicHttpParams();
  int timeoutMilliSeconds=timeout * 1000;
  HttpConnectionParams.setConnectionTimeout(params,timeoutMilliSeconds);
  HttpConnectionParams.setSoTimeout(params,timeoutMilliSeconds);
  DefaultHttpClient client=new DefaultHttpClient(params);
  if (userName != null && !"".equals(userName)) {
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST,AuthScope.ANY_PORT),new UsernamePasswordCredentials(userName,password));
    localContext=new BasicHttpContext();
    BasicScheme basicAuth=new BasicScheme();
    localContext.setAttribute("preemptive-auth",basicAuth);
    client.addRequestInterceptor(new PreemptiveAuth(),0);
  }
  String userAgent="ArtifactoryBuildClient/" + CLIENT_VERSION;
  HttpProtocolParams.setUserAgent(client.getParams(),userAgent);
  return client;
}
 

Example 15

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

Source file: BetterHttpRequestBase.java

  20 
vote

public BetterHttpResponse send() throws ConnectException {
  BetterHttpRequestRetryHandler retryHandler=new BetterHttpRequestRetryHandler(maxRetries);
  httpClient.setHttpRequestRetryHandler(retryHandler);
  HttpContext context=new BasicHttpContext();
  boolean retry=true;
  IOException cause=null;
  while (retry) {
    try {
      return httpClient.execute(request,this,context);
    }
 catch (    IOException e) {
      cause=e;
      retry=retryRequest(retryHandler,cause,context);
    }
catch (    NullPointerException e) {
      cause=new IOException("NPE in HttpClient" + e.getMessage());
      retry=retryRequest(retryHandler,cause,context);
    }
 finally {
      if (oldTimeout != BetterHttp.getSocketTimeout()) {
        BetterHttp.setSocketTimeout(oldTimeout);
      }
    }
  }
  ConnectException ex=new ConnectException();
  ex.initCause(cause);
  throw ex;
}
 

Example 16

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

Source file: ConexionSii.java

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

From project exo.social.client, under directory /src/main/java/org/exoplatform/social/client/core/net/.

Source file: SocialHttpClientImpl.java

  19 
vote

private SocialHttpClientImpl(ClientConnectionManager ccm,HttpParams params){
  delegate=new DefaultHttpClient(ccm,params){
    @Override protected BasicHttpProcessor createHttpProcessor(){
      BasicHttpProcessor processor=super.createHttpProcessor();
      return processor;
    }
    @Override protected HttpContext createHttpContext(){
      HttpContext context=new BasicHttpContext();
      context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY,getAuthSchemes());
      context.setAttribute(ClientContext.COOKIESPEC_REGISTRY,getCookieSpecs());
      context.setAttribute(ClientContext.CREDS_PROVIDER,getCredentialsProvider());
      return context;
    }
  }
;
}
 

Example 18

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

Source file: AndroidHttpClient.java

  19 
vote

private AndroidHttpClient(ClientConnectionManager ccm,HttpParams params){
  this.delegate=new DefaultHttpClient(ccm,params){
    @Override protected BasicHttpProcessor createHttpProcessor(){
      BasicHttpProcessor processor=super.createHttpProcessor();
      processor.addRequestInterceptor(sThreadCheckInterceptor);
      return processor;
    }
    @Override protected HttpContext createHttpContext(){
      HttpContext context=new BasicHttpContext();
      context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY,getAuthSchemes());
      context.setAttribute(ClientContext.COOKIESPEC_REGISTRY,getCookieSpecs());
      context.setAttribute(ClientContext.CREDS_PROVIDER,getCredentialsProvider());
      return context;
    }
  }
;
}