@Test
  public void testConnectionBasedAuthOnlyIfChallenged() throws Exception {
    HttpRequest request = new BasicHttpRequest("GET", "/");
    HttpContext context = new BasicHttpContext();

    AuthState authstate = new AuthState();

    BasicScheme authscheme =
        new BasicScheme() {

          @Override
          public boolean isConnectionBased() {
            return true;
          }
        };

    BasicHeader challenge = new BasicHeader(AUTH.WWW_AUTH, "BASIC realm=auth-realm");
    authscheme.processChallenge(challenge);

    Credentials creds = new UsernamePasswordCredentials("user", "secret");

    authstate.setState(AuthProtocolState.SUCCESS);
    authstate.update(authscheme, creds);

    context.setAttribute(ClientContext.TARGET_AUTH_STATE, authstate);

    HttpRequestInterceptor interceptor = new RequestTargetAuthentication();
    interceptor.process(request, context);
    Header header = request.getFirstHeader(AUTH.WWW_AUTH_RESP);
    Assert.assertNull(header);
  }
示例#2
0
  @Override
  public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    boolean retry = true;

    Boolean b = (Boolean) context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
    boolean sent = (b != null && b.booleanValue());

    if (executionCount > maxRetries) {
      // 尝试次数超过用户定义的测试,默认5次
      retry = false;
    } else if (exceptionBlacklist.contains(exception.getClass())) {
      // 线程被用户中断,则不继续尝试
      retry = false;
    } else if (exceptionWhitelist.contains(exception.getClass())) {
      retry = true;
    } else if (!sent) {
      retry = true;
    }

    if (retry) {
      HttpUriRequest currentReq =
          (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
      retry = currentReq != null && !"POST".equals(currentReq.getMethod());
    }

    if (retry) {
      // 休眠1秒钟后再继续尝试
      SystemClock.sleep(RETRY_SLEEP_TIME_MILLIS);
    } else {
      exception.printStackTrace();
    }

    return retry;
  }
示例#3
0
    public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {
      AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
      if (authState.getAuthScheme() != null) {
        return;
      }

      AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
      if (authScheme == null) {
        return;
      }

      CredentialsProvider credsProvider =
          (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
      HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

      Credentials creds =
          credsProvider.getCredentials(
              new AuthScope(targetHost.getHostName(), targetHost.getPort()));
      if (creds == null) {
        return;
      }

      authState.setAuthScheme(authScheme);
      authState.setCredentials(creds);
    }
示例#4
0
  static void testProtectedResource() throws ClientProtocolException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpget = new HttpGet(url);
    HttpResponse response = httpclient.execute(httpget, localContext);

    AuthState proxyAuthState =
        (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);

    System.out.println("Proxy auth scope: " + proxyAuthState.getAuthScope());
    System.out.println("Proxy auth scheme: " + proxyAuthState.getAuthScheme());
    System.out.println("Proxy auth credentials: " + proxyAuthState.getCredentials());

    AuthState targetAuthState =
        (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
    System.out.println("Target auth scope: " + targetAuthState.getAuthScope());
    System.out.println("Target auth scheme: " + targetAuthState.getAuthScheme());
    System.out.println("Target auth credentials: " + targetAuthState.getCredentials());

    HttpEntity entity = response.getEntity();
    String charset = HttpclientTutorial.getResponseCharset(response);
    System.out.println("charset:" + charset);
    HttpclientTutorial.output(entity, charset);

    EntityUtils.consume(entity);
  }
    public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {

      AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);

      if (authState.getAuthScheme() != null || authState.hasAuthOptions()) {
        return;
      }

      // If no authState has been established and this is a PUT or POST request, add preemptive
      // authorisation
      String requestMethod = request.getRequestLine().getMethod();
      if (requestMethod.equals(HttpPut.METHOD_NAME) || requestMethod.equals(HttpPost.METHOD_NAME)) {
        CredentialsProvider credentialsProvider =
            (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
        HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        Credentials credentials =
            credentialsProvider.getCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()));
        if (credentials == null) {
          throw new HttpException("No credentials for preemptive authentication");
        }
        authState.update(authScheme, credentials);
      }
    }
  @Test
  public void testPreemptiveAuthenticationFailure() throws Exception {
    CountingAuthHandler requestHandler = new CountingAuthHandler();
    this.localServer.register("*", requestHandler);
    this.localServer.start();

    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("test", "stuff"));

    this.httpclient.setCredentialsProvider(credsProvider);

    HttpHost targethost = getServerHttp();

    HttpContext context = new BasicHttpContext();
    AuthCache authCache = new BasicAuthCache();
    authCache.put(targethost, new BasicScheme());
    context.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet httpget = new HttpGet("/");

    HttpResponse response1 = this.httpclient.execute(targethost, httpget, context);
    HttpEntity entity1 = response1.getEntity();
    Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response1.getStatusLine().getStatusCode());
    Assert.assertNotNull(entity1);
    EntityUtils.consume(entity1);

    Assert.assertEquals(1, requestHandler.getCount());
  }
示例#7
0
    public void process(HttpRequest request, HttpContext context)
        throws HttpException, IOException {

      AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);

      if (request.getFirstHeader("Authorization") != null) {
        // Using OAuth, leave as is
      } else if (request.getFirstHeader("X-No-Auth") != null) {
        // No auth required, leave as is
      } else {
        // If no auth scheme avaialble yet, try to initialize it preemptively
        if (authState.getAuthScheme() == null) {
          AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
          CredentialsProvider credsProvider =
              (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
          HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
          if (authScheme != null) {
            Credentials creds =
                credsProvider.getCredentials(
                    new AuthScope(targetHost.getHostName(), targetHost.getPort()));
            if (creds == null) {
              throw new HttpException("No credentials for preemptive authentication");
            } else {
              authState.setAuthScheme(authScheme);
              authState.setCredentials(creds);
            }
          }
        }
      }
    }
    public void doReadLoop() {
      HttpContext context = new BasicHttpContext();
      context.setAttribute(CX_SOCKET, rawSocket);

      while (!Thread.interrupted() && this.htConn.isOpen() && HttpServer.this.shouldRun) {
        // Clear the context from any auth settings; since this is done
        // anew on each connection..
        context.removeAttribute(CX_AUTH);

        try {
          HttpServer.this.httpService.handleRequest(htConn, context);
        } catch (ConnectionClosedException ex_closed) {
          break;
        } catch (IOException ex) {
          if (!closeRequested) {
            ex.printStackTrace();
          }
          break;
        } catch (HttpException ex) {
          ex.printStackTrace();
          break;
        } catch (ResponseHandledException ex) {
          break;
        }
      }
      bail();
    }
  @Override
  public boolean retryRequest(IOException e, int executionCount, HttpContext context) {
    boolean retry = true;

    Boolean b = (Boolean) context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
    boolean sent = (b != null && b);

    if (executionCount > maxRetries) {
      retry = false;
    } else if (isInList(exceptionWhiteList, e)) {
      retry = true;
    } else if (isInList(exceptionBlackList, e)) {
      retry = false;
    } else if (!sent) {
      retry = true;
    }

    if (retry) {
      HttpUriRequest request = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
      if (request == null) {
        return false;
      }
    }

    if (retry) {
      SystemClock.sleep(retrySleepTimeMS);
    } else {
      e.printStackTrace();
    }

    return retry;
  }
    @Override
    protected Void doInBackground(Void... params) {
      // TODO Auto-generated method stub
      try {

        apiParams = new ArrayList<NameValuePair>();
        apiParams.add(
            new BasicNameValuePair(
                AppProperties.DATABASE, session.getValue(AppProperties.DATABASE)));
        apiParams.add(
            new BasicNameValuePair("profileid", session.getValue(AppProperties.PROFILE_ID)));
        apiParams.add(new BasicNameValuePair("chat_sent_time", last_chat_time));
        apiParams.add(new BasicNameValuePair("userid", userid));
        apiParams.add(new BasicNameValuePair("name", "Brijesh Kushwaha"));
        apiParams.add(new BasicNameValuePair("message", msg));
        apiParams.add(
            new BasicNameValuePair(
                "photo",
                "https://ebdd192075d95c350eef-28241eefd51f43f0990a7c61585ebde0.ssl.cf2.rackcdn.com/1000000002_1405785647.jpg"));
        apiParams.add(new BasicNameValuePair("auth", session.getValue(AppProperties.PROFILE_ID)));
        apiParams.add(
            new BasicNameValuePair("PHPSESSID", session.getValue(AppProperties.SESSION_ID)));
        Log.e("Chat NEW Parameters", apiParams.toString());

        Log.e("url", url);

        post = new HttpPost(url);
        post.addHeader("PHPSESSID", session.getValue(AppProperties.SESSION_ID));
        Log.e("PHPSESSID", session.getValue(AppProperties.SESSION_ID));
        post.setEntity(new UrlEncodedFormEntity(apiParams));
        BasicCookieStore cookieStore = new BasicCookieStore();
        HttpClient client = new DefaultHttpClient();
        // Create local HTTP context
        HttpContext localContext = new BasicHttpContext();
        // Bind custom cookie store to the local context
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        rChatUpdate = client.execute(post);
        status = rChatUpdate.getStatusLine().getStatusCode();
        System.out.println("Stage -1");
        if (status == 200) {
          System.out.println("Satus 200 obtained from Quipmate");
          HttpEntity e = rChatUpdate.getEntity();
          System.out.println("Stage 1");
          String d = EntityUtils.toString(e);
          if (d != null) {

            Log.e("Chat", d.toString());
          }
        }
      } catch (Exception e) {
        System.out.println("Some Unknown exception occured");
        e.printStackTrace();
      }
      return null;
    }
 @Override
 protected HttpContext createHttpContext() {
   HttpContext context = new BasicHttpContext();
   context.setAttribute(ClientContext.SCHEME_REGISTRY, getConnectionManager().getSchemeRegistry());
   context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes());
   context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs());
   context.setAttribute(ClientContext.COOKIE_STORE, getCookieStore());
   context.setAttribute(ClientContext.CREDS_PROVIDER, getCredentialsProvider());
   return context;
 }
示例#12
0
  public void exception(NHttpServerConnection conn, Exception ex) {
    if (ex instanceof IOException) {
      logIOException(conn, (IOException) ex);

      metrics.incrementFaultsReceiving();

      ProtocolState state = SourceContext.getState(conn);
      if (state == ProtocolState.REQUEST_BODY || state == ProtocolState.REQUEST_HEAD) {
        informReaderError(conn);
      } else if (state == ProtocolState.RESPONSE_BODY || state == ProtocolState.RESPONSE_HEAD) {
        informWriterError(conn);
      } else if (state == ProtocolState.REQUEST_DONE) {
        informWriterError(conn);
      } else if (state == ProtocolState.RESPONSE_DONE) {
        informWriterError(conn);
      }

      SourceContext.updateState(conn, ProtocolState.CLOSED);
      sourceConfiguration.getSourceConnections().shutDownConnection(conn);
    } else if (ex instanceof HttpException) {
      try {
        if (conn.isResponseSubmitted()) {
          sourceConfiguration.getSourceConnections().shutDownConnection(conn);
          return;
        }
        HttpContext httpContext = conn.getContext();

        HttpResponse response =
            new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_REQUEST, "Bad request");
        response.setParams(
            new DefaultedHttpParams(sourceConfiguration.getHttpParams(), response.getParams()));
        response.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);

        // Pre-process HTTP request
        httpContext.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        httpContext.setAttribute(ExecutionContext.HTTP_REQUEST, null);
        httpContext.setAttribute(ExecutionContext.HTTP_RESPONSE, response);

        sourceConfiguration.getHttpProcessor().process(response, httpContext);

        conn.submitResponse(response);
        SourceContext.updateState(conn, ProtocolState.CLOSED);
        conn.close();
      } catch (Exception ex1) {
        log.error(ex.getMessage(), ex);
        SourceContext.updateState(conn, ProtocolState.CLOSED);
        sourceConfiguration.getSourceConnections().shutDownConnection(conn);
      }
    } else {
      log.error("Unexoected error: " + ex.getMessage(), ex);
      SourceContext.updateState(conn, ProtocolState.CLOSED);
      sourceConfiguration.getSourceConnections().shutDownConnection(conn);
    }
  }
  @Test
  public void testAuthStateNotSet() throws Exception {
    HttpRequest request = new BasicHttpRequest("GET", "/");
    HttpContext context = new BasicHttpContext();

    context.setAttribute(ClientContext.TARGET_AUTH_STATE, null);

    HttpRequestInterceptor interceptor = new RequestTargetAuthentication();
    interceptor.process(request, context);
    Header header = request.getFirstHeader(AUTH.WWW_AUTH_RESP);
    Assert.assertNull(header);
  }
示例#14
0
文件: JsonUtil.java 项目: tyhu/Git
  /**
   * Return the HTTP Get result as String given these parameters.
   *
   * @param url The url for the Get request.
   * @param cookies The cookie String to be appended to the request.
   * @param domain The domain to be set into the cookie if any.
   * @return String The result of the HTTP Get request.
   */
  private String getHttpGetResponseString(String url, String cookies, String domain) {
    StringBuilder total = new StringBuilder();
    BufferedReader r = null;

    try {
      HttpClient httpclient = new DefaultHttpClient();
      HttpGet httpget = new HttpGet(url);

      HttpContext localContext = new BasicHttpContext();
      if (cookies != null) {
        // Split the Cookie string into cookies, and put them into the HttpContext
        BasicCookieStore cookieStore = new BasicCookieStore();
        StringTokenizer st = new StringTokenizer(cookies, "[;]");
        while (st.hasMoreElements()) {
          String ele = (String) st.nextElement();
          int splitterIdx = ele.indexOf('=');

          String key = ele.substring(0, splitterIdx);
          String val = ele.substring(splitterIdx + 1, ele.length());

          BasicClientCookie cookie = new BasicClientCookie(key, val);
          if (domain != null) cookie.setDomain(domain);
          cookie.setSecure(false);
          cookie.setVersion(0);
          cookieStore.addCookie(cookie);
        }
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
      }
      // Execute HTTP Post Request
      HttpResponse response = httpclient.execute(httpget, localContext);
      r = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
      String line = null;
      while ((line = r.readLine()) != null) {
        total.append(line);
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (OutOfMemoryError e) {
      // e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (r != null) r.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return total.toString();
  }
 public void process(final HttpResponse response, final HttpContext context)
     throws HttpException, IOException {
   AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
   if (authState != null) {
     AuthScheme authScheme = authState.getAuthScheme();
     // Stick the auth scheme to the local context, so
     // we could try to authenticate subsequent requests
     // preemptively
     if (authScheme instanceof DigestScheme) {
       context.setAttribute("preemptive-auth", authScheme);
     }
   }
 }
示例#16
0
  public static HttpResponse post(
      String url, List<NameValuePair> params, RequestConfig config, CookieStore cookieStore)
      throws IOException {
    CloseableHttpClient client =
        HttpClients.custom().setUserAgent(Constants.DEFAULT_USER_AGENT).build();
    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

    HttpPost post = new HttpPost(url);
    post.setEntity(new UrlEncodedFormEntity(params));
    post.setConfig(config);
    HttpResponse response = client.execute(post, localContext);
    return response;
  }
示例#17
0
 private static String getUrlAfterRedirects(HttpContext context) {
   String lastRedirectUrl = (String) context.getAttribute(LAST_REDIRECT_URL);
   if (lastRedirectUrl != null) return lastRedirectUrl;
   else {
     HttpUriRequest currentReq =
         (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
     HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
     String currentUrl =
         (currentReq.getURI().isAbsolute())
             ? currentReq.getURI().toString()
             : (currentHost.toURI() + currentReq.getURI());
     return currentUrl;
   }
 }
示例#18
0
  public void signUp(View view) {
    EditText email = (EditText) findViewById(R.id.email);
    EditText pw = (EditText) findViewById(R.id.password);
    EditText nameField = (EditText) findViewById(R.id.name);
    String username = email.getText().toString();
    String password = pw.getText().toString();
    String name = nameField.getText().toString();
    try {
      URI uri = new URI("http://severe-leaf-6733.herokuapp.com/users");
      DefaultHttpClient client = new DefaultHttpClient();
      HttpPost post = new HttpPost(uri);

      JSONObject json = new JSONObject();
      JSONObject m = new JSONObject();
      m.put("name", name);
      m.put("email", username);
      m.put("password", password);
      json.put("user", m);

      StringEntity se = new StringEntity(json.toString());
      post.setEntity(se);
      post.setHeader("Accept", "application/json");
      post.setHeader("Content-type", "application/json");
      BasicResponseHandler responseHandler = new BasicResponseHandler();
      String responseString = client.execute(post, responseHandler);

      GsonBuilder g = new GsonBuilder();
      g.setDateFormat("E MMM d HH:mm:ss Z y");
      Gson gson = g.create();
      User um = gson.fromJson(responseString, User.class);

      if (um.getID() != 0) {
        CookieStore cookieStore = client.getCookieStore();
        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        Global.localContext = localContext;
        Global.client = client;
        Global.user_id = um.getID();

        Intent myIntent = new Intent(getApplicationContext(), Root.class);
        startActivity(myIntent);
      } else {
        Toast.makeText(this, "Unable to Sign Up", Toast.LENGTH_LONG).show();
      }
    } catch (Exception e) {
      Log.e("Sign Up Error", e.getMessage());
    }
  }
示例#19
0
  @Override
  public void run() {
    uploadInitialising();
    try {
      if (fireDriveAccount.loginsuccessful) {
        httpContext = fireDriveAccount.getHttpContext();

        if (fireDriveAccount.isPremium()) {
          maxFileSizeLimit = 53687091200l; // 50 GB
        } else {
          maxFileSizeLimit = 1073741824l; // 1 GB
        }

      } else {
        httpContext.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore());
      }

      if (file.length() > maxFileSizeLimit) {
        throw new NUMaxFileSizeException(maxFileSizeLimit, file.getName(), getHost());
      }

      normalUpload();
      uploadFinished();
    } catch (NUException ex) {
      ex.printError();
      uploadInvalid();
    } catch (Exception e) {
      NULogger.getLogger().log(Level.INFO, "Exception: {0}", e);
      uploadFailed();
    }
  }
 @Override
 public void process(HttpResponse response, HttpContext context)
     throws HttpException, IOException {
   CookieStore cookieStore = (CookieStore) context.getAttribute(ClientContext.COOKIE_STORE);
   for (Header header : response.getAllHeaders()) {
     if (!header.getName().equalsIgnoreCase("Set-Cookie")) {
       continue;
     }
     Matcher matcher = pattern.matcher(header.getValue());
     if (!matcher.find()) {
       continue;
     }
     for (Cookie cookie : cookieStore.getCookies()) {
       if (cookie.getName().equalsIgnoreCase(matcher.group(1))) {
         if (cookie instanceof BasicClientCookie) {
           ((BasicClientCookie) cookie).setValue('"' + cookie.getValue() + '"');
         } else if (cookie instanceof BasicClientCookie2) {
           ((BasicClientCookie2) cookie).setValue('"' + cookie.getValue() + '"');
         } else {
           Log.w(TAG, "unhandled cookie implementation " + cookie.getClass().getName());
         }
         break;
       }
     }
   }
 }
示例#21
0
        @Override
        public boolean retryRequest(
            IOException exception, int executionCount, HttpContext context) {
          // 设置恢复策略,在发生异常时候将自动重试N次
          if (executionCount >= RETRIED_TIME) {
            // Do not retry if over max retry count
            Logger.getLogger().e("Do not retry if over max retry count:" + executionCount);
            return false;
          }

          if (exception instanceof NoHttpResponseException) {
            // Retry if the server dropped connection on us
            Logger.getLogger()
                .i(
                    "Retry if the server dropped connection on us:exception instanceof NoHttpResponseException");
            return true;
          }

          if (exception instanceof SSLHandshakeException) {
            // Do not retry on SSL handshake exception
            Logger.getLogger().e("Do not retry on SSL handshake SSLHandshakeException ");
            return false;
          }

          HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);

          boolean idempotent = (request instanceof HttpEntityEnclosingRequest);
          if (!idempotent) {
            // Retry if the request is considered idempotent
            Logger.getLogger().i("Retry if the request is considered idempotent");
            return true;
          }

          return false;
        }
示例#22
0
文件: Network.java 项目: ndong211/bo
        public void process(final HttpRequest request, final HttpContext context)
            throws HttpException, IOException {
          Locale locale = Locale.getDefault();
          request.setHeader(
              "Accept-Language", (locale.getLanguage() + "-" + locale.getCountry()).toLowerCase());
          request.setHeader("Accept-Encoding", "gzip");
          AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
          // HttpHost targetHost = (HttpHost)
          // context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
          if (true /*(INFO.HOST_IP.equals(targetHost.getHostName())) && (INFO.HOST_PORT == targetHost.getPort())*/) {
            authState.setAuthScheme(new BasicScheme());

            /* username = "******";
            password = "******";*/
            if (username == null) {
              //            		username = appContext.getSharedPreferences(BaseActivity.SETTING_INFOS,
              // Context.MODE_PRIVATE).getString(BaseActivity.NAME, null);
              //            		password = appContext.getSharedPreferences(BaseActivity.SETTING_INFOS,
              // Context.MODE_PRIVATE).getString(BaseActivity.PASSWORD, null);
            }
            // INFO.Log("username", username+"");
            if (username != null) {
              authState.setCredentials(new UsernamePasswordCredentials(username, password));
            }
          }
        }
示例#23
0
  /**
   * 设置Cookie 方法2
   *
   * <p>httpclient.execute(request, context) 方法进行添加
   *
   * @param cookies
   * @return
   */
  public HttpContext getetRequestCookieContext(Map<String, String> cookies) {
    HttpContext localContext = null;
    if (cookies != null && cookies.size() > 0) {
      BasicCookieStore cookieStore = new BasicCookieStore();

      for (Entry<String, String> c : cookies.entrySet()) {
        BasicClientCookie cookie = new BasicClientCookie(c.getKey(), c.getValue());
        cookie.setDomain("sina.com");
        cookie.setPath("/");
        cookieStore.addCookie(cookie);
      }
      localContext = new BasicHttpContext();
      localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
    }
    return localContext;
  }
  @Override
  public void run() {
    try {
      if (file.length() > fileSizeLimit) {
        throw new NUMaxFileSizeException(fileSizeLimit, file.getName(), this.getHost());
      }

      if (solidfilesAccount.loginsuccessful) {
        httpContext = solidfilesAccount.getHttpContext();
      } else {
        cookieStore = new BasicCookieStore();
        httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
      }

      uploadInitialising();
      fileupload();
    } catch (NUException ex) {
      ex.printError();
      uploadInvalid();
    } catch (Exception e) {
      Logger.getLogger(Solidfiles.class.getName()).log(Level.SEVERE, null, e);

      uploadFailed();
    }
  }
示例#25
0
  public void setRequest(
      com.hzth.myapp.myHttpClient.protocol.Request request, CallbackInterface callback)
      throws Exception {
    super.setRequest(request, callback);

    // request settings
    int port = request.getUrl().getPort();
    context = new BasicHttpContext(null);
    host = new HttpHost(request.getUrl().getHost(), port == -1 ? 80 : port);

    conn = new DefaultHttpClientConnection();
    connStrategy = new DefaultConnectionReuseStrategy();

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
  }
示例#26
0
文件: Web.java 项目: Yogu/BoxContacts
 private void createContext() {
   synchronized (lock) {
     if (context == null) {
       context = new BasicHttpContext();
       cookieStore = new BasicCookieStore();
       context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
     }
   }
 }
    public void process(HttpRequest request, HttpContext context)
        throws HttpException, IOException {
      HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

      UserPasswordAuthentication creds;
      synchronized (this) {
        creds = credentials.get(targetHost);
      }

      if (creds != null) {
        AuthScope scope = new AuthScope(targetHost);

        BasicCredentialsProvider credProvider = new BasicCredentialsProvider();
        credProvider.setCredentials(
            scope, new UsernamePasswordCredentials(creds.getUsername(), creds.getPassword()));
        context.setAttribute(ClientContext.CREDS_PROVIDER, credProvider);
      }
    }
  @Override
  public void process(final HttpRequest request, final HttpContext context)
      throws HttpException, IOException {
    AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);

    if (authState.getAuthScheme() == null) {
      Credentials creds = new UsernamePasswordCredentials(myUsername, myPassword);
      authState.update(new BasicScheme(), creds);
    }
  }
示例#29
0
 public static String getRedirectedUrl(String url) {
   DefaultHttpClient client = new DefaultHttpClient();
   HttpGet get = new HttpGet(url);
   try {
     HttpContext context = new BasicHttpContext();
     HttpResponse response = client.execute(get, context);
     if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
       throw new IOException(response.getStatusLine().toString());
     HttpUriRequest currentReq =
         (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
     HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
     return currentHost.toURI() + currentReq.getURI();
   } catch (ClientProtocolException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return url;
 }
示例#30
0
  public static HttpResponse get(
      String url, List<NameValuePair> params, RequestConfig config, CookieStore cookieStore)
      throws IOException {
    CloseableHttpClient client =
        HttpClients.custom().setUserAgent(Constants.DEFAULT_USER_AGENT).build();
    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

    String reqUrl = "";
    if (params != null && params.size() > 0) {
      reqUrl = url + "?" + URLEncodedUtils.format(params, "utf-8");
    } else {
      reqUrl = url;
    }
    HttpGet get = new HttpGet(reqUrl);
    get.setConfig(config);
    HttpResponse response = client.execute(get, localContext);
    return response;
  }