@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);
  }
 @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;
 }
Example #3
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 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());
  }
Example #5
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);
  }
    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 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();
    }
  }
Example #8
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();
    }
  }
Example #9
0
 private void createContext() {
   synchronized (lock) {
     if (context == null) {
       context = new BasicHttpContext();
       cookieStore = new BasicCookieStore();
       context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
     }
   }
 }
    @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
        public void process(HttpRequest request, HttpContext context)
            throws HttpException, IOException {
          BasicClientCookie cookie = new BasicClientCookie(cookieName, cookieValue);
          cookie.setVersion(0);
          cookie.setPath("/");
          cookie.setDomain(jetty.getBaseUrl().getHost());

          CookieStore cookieStore = new BasicCookieStore();
          CookieSpecRegistry registry =
              (CookieSpecRegistry) context.getAttribute(ClientContext.COOKIESPEC_REGISTRY);
          String policy = HttpClientParams.getCookiePolicy(request.getParams());
          CookieSpec cookieSpec = registry.getCookieSpec(policy, request.getParams());
          // Add the cookies to the request
          List<Header> headers = cookieSpec.formatCookies(Collections.singletonList(cookie));
          for (Header header : headers) {
            request.addHeader(header);
          }
          context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
          context.setAttribute(ClientContext.COOKIE_SPEC, cookieSpec);
        }
  @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);
  }
Example #13
0
  /**
   * 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();
  }
Example #14
0
  protected void createGetMethod(String url) {
    getMethod = new HttpGet(url);
    getMethod.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, true);
    state.setAttribute(ClientContext.CREDS_PROVIDER, new WsdlCredentialsProvider());

    if (SoapUI.getSettings().getBoolean(HttpSettings.AUTHENTICATE_PREEMPTIVELY)) {
      if (!StringUtils.isNullOrEmpty(getUsername()) && !StringUtils.isNullOrEmpty(getPassword())) {
        UsernamePasswordCredentials creds =
            new UsernamePasswordCredentials(getUsername(), getPassword());
        getMethod.addHeader(BasicScheme.authenticate(creds, "utf-8", false));
      }
    }
  }
 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);
     }
   }
 }
  public void testInsertEtag() throws Exception {
    MockHttpResponse response =
        new MockHttpResponse() {
          @Override
          public boolean containsHeader(String name) {
            return true;
          }

          public org.apache.http.StatusLine getStatusLine() {
            return new BasicStatusLine(new ProtocolVersion("http", 1, 1), 200, "OK");
          };

          @Override
          public Header getFirstHeader(String name) {
            if (name.equals(ETag.ETAG)) {
              return new BasicHeader(ETag.ETAG, "test-etag");
            } else if (name.equals(ETag.LAST_MODIFIED)) {
              return new BasicHeader(ETag.LAST_MODIFIED, "last-modified");
            }
            return super.getFirstHeader(name);
          }
        };
    HttpContext context = new BasicHttpContext();
    context.setAttribute(
        ExecutionContext.HTTP_REQUEST,
        new MockHttpRequest() {
          @Override
          public RequestLine getRequestLine() {
            return new BasicRequestLine("GET", "test.com", new ProtocolVersion("http", 1, 1));
          }
        });
    final HttpHost targetHost = new HttpHost("test.com");
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost);
    interceptor.onPostCall(response, context);
    ETag etag = interceptor.helper.getETag("test.com");
    assertEquals("test-etag", etag.etag);
    assertEquals("last-modified", etag.lastModified);
  }
Example #17
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;
  }
Example #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());
    }
  }
  public void init(String penguinAppId, String baseURL) {
    this.penguinAppId = penguinAppId;
    this.baseURL = baseURL;

    // Create a local instance of cookie store
    CookieStore cookieStore = new BasicCookieStore();

    // Create local HTTP context
    localContext = new BasicHttpContext();

    // Bind custom cookie store to the local context
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    httpclient = new DefaultHttpClient();
  }
Example #20
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;
  }
    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);
      }
    }
Example #22
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;
  }
  @Test
  public void testNoTargetAuthForConnectRequests() throws Exception {
    HttpRequest request = new BasicHttpRequest("CONNECT", "www.somedomain.com");
    HttpContext context = new BasicHttpContext();

    BasicScheme authscheme = new BasicScheme();
    Credentials creds = new UsernamePasswordCredentials("user", "secret");
    BasicHeader challenge = new BasicHeader(AUTH.WWW_AUTH, "BASIC realm=auth-realm");
    authscheme.processChallenge(challenge);

    AuthState authstate = new AuthState();
    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);
  }
Example #24
0
 @Override
 public boolean isRedirected(HttpRequest request, HttpResponse res, HttpContext context)
     throws ProtocolException {
   Header header = res.getFirstHeader("Location");
   // HttpClientUtil.printResponseHeaders(res) ;O
   if (header != null) {
     String location = header.getValue();
     if (location.indexOf("://") > 0) {
       String site = (String) context.getAttribute("crawler.site");
       int idx = location.indexOf("://");
       String hostName = location.substring(idx + 3);
       idx = hostName.indexOf('/');
       if (idx > 0) {
         hostName = hostName.substring(0, idx);
       }
       context.setAttribute("url.redirect", location);
       if (!hostName.endsWith(site)) return false;
     }
   }
   return super.isRedirected(request, res, context);
 }
 private void initHttp() {
   if (httpclientdirect == null) {
     httpclientdirect = AndroidHttpClient.newInstance(null);
     httpctxt = new BasicHttpContext();
     httpctxt.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore());
     // login
     try {
       List<NameValuePair> formparams = new ArrayList<NameValuePair>();
       formparams.add(new BasicNameValuePair("userid", u));
       formparams.add(new BasicNameValuePair("passwd", p));
       formparams.add(new BasicNameValuePair("login", "Log+In"));
       UrlEncodedFormEntity entity;
       entity = new UrlEncodedFormEntity(formparams, "UTF-8");
       HttpPost httppost = new HttpPost(getUrl() + "login.php");
       httppost.setEntity(entity);
       directConnectExecute(httppost);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
  @Test
  public void testTargetAuth() throws Exception {
    HttpRequest request = new BasicHttpRequest("GET", "/");
    HttpContext context = new BasicHttpContext();

    BasicScheme authscheme = new BasicScheme();
    Credentials creds = new UsernamePasswordCredentials("user", "secret");
    BasicHeader challenge = new BasicHeader(AUTH.WWW_AUTH, "BASIC realm=auth-realm");
    authscheme.processChallenge(challenge);

    AuthState authstate = new AuthState();
    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.assertNotNull(header);
    Assert.assertEquals("Basic dXNlcjpzZWNyZXQ=", header.getValue());
  }
Example #27
0
  @Override
  protected String doInBackground(String... params) {
    if (params.length > 0) {
      String url = params[0];
      String username = params[1];
      String password = params[2];

      try {

        AndroidHttpClient httpClient = AndroidHttpClient.newInstance("ExceedVote connection");

        URL urlObj = new URL(url);
        HttpHost host = new HttpHost(urlObj.getHost(), urlObj.getPort(), urlObj.getProtocol());
        AuthScope scope = new AuthScope(urlObj.getHost(), urlObj.getPort());
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);

        CredentialsProvider cp = new BasicCredentialsProvider();
        cp.setCredentials(scope, creds);
        HttpContext credContext = new BasicHttpContext();
        credContext.setAttribute(ClientContext.CREDS_PROVIDER, cp);

        HttpGet job = new HttpGet(url);
        HttpResponse response = httpClient.execute(host, job, credContext);
        StatusLine status = response.getStatusLine();
        Log.d("TAG", status.getStatusCode() + "");
        if (status.getStatusCode() != 200) {
          Log.d("ERROR", EntityUtils.toString(response.getEntity()));
          return "error";
        }
        HttpEntity entity = response.getEntity();
        String s_response = EntityUtils.toString(entity);
        httpClient.close();
        return s_response;
      } catch (Exception e) {
        Log.d("TAG", e.getMessage());
        return "error";
      }
    }
    return "error";
  }
  /**
   * Performs an HTTP GET request to the specified url.
   *
   * @param url The web address to post the request to
   * @return The result of the request
   * @throws Exception
   */
  public static String executeHttpGet(String url) throws Exception {
    BufferedReader in = null;
    try {

      HttpClient client = getHttpClient();

      // Cookie stuff that may break
      CookieStore cookieStore = new BasicCookieStore();
      HttpContext httpContext = new BasicHttpContext();
      httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

      // HttpResponse response1 = client.execute(yourMethod1, httpContext);

      HttpGet request = new HttpGet();
      request.setURI(new URI(url));
      HttpResponse response = client.execute(request, httpContext);
      in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

      StringBuffer sb = new StringBuffer("");
      String line = "";
      String NL = System.getProperty("line.separator");
      while ((line = in.readLine()) != null) {
        sb.append(line + NL);
      }
      in.close();

      String result = sb.toString();
      return result;
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
Example #29
0
 /**
  * HttpClient 登录代码如下
  *
  * @param url
  * @throws Exception
  */
 private void login(String url) throws Exception {
   //		HttpClient 登录代码如下
   DefaultHttpClient client = new DefaultHttpClient();
   HttpGet get = new HttpGet(url);
   HttpContext context = new BasicHttpContext();
   CookieStore cookieStore = new BasicCookieStore();
   context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
   HttpResponse response = client.execute(get, context);
   if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
     // 根据你的逻辑,判断返回的值是不是表示已经登录成功
     //			if (isLoginSuccess()) {
     List<Cookie> cookies = cookieStore.getCookies();
     if (!cookies.isEmpty()) {
       for (int i = cookies.size(); i > 0; i--) {
         Cookie cookie = cookies.get(i - 1);
         if (cookie.getName().equalsIgnoreCase(PHPSESSID)) { // "jsessionid"
           // 使用一个常量来保存这个cookie,用于做session共享之用
           sessionCookie = cookie;
         }
       }
     }
     //			}
   }
 }
 /**
  * @see #HttpConnector(HttpClient, long)
  * @since 5.7
  */
 public HttpConnector(HttpClient http, HttpContext ctx, int httpConnectionTimeout) {
   ctx.setAttribute(HttpClientContext.COOKIE_STORE, new BasicCookieStore());
   this.http = http;
   this.httpConnectionTimeout = httpConnectionTimeout;
   this.ctx = ctx;
 }