Example usage for org.apache.http.protocol HTTP ASCII

List of usage examples for org.apache.http.protocol HTTP ASCII

Introduction

In this page you can find the example usage for org.apache.http.protocol HTTP ASCII.

Prototype

String ASCII

To view the source code for org.apache.http.protocol HTTP ASCII.

Click Source Link

Usage

From source file:org.mobicents.servlet.restcomm.util.HttpUtils.java

public static Map<String, String> toMap(final HttpEntity entity) throws IllegalStateException, IOException {

    String contentType = null;//  w ww . j  av  a2  s. c  o  m
    String charset = null;

    contentType = EntityUtils.getContentMimeType(entity);
    charset = EntityUtils.getContentCharSet(entity);

    List<NameValuePair> parameters = null;
    if (contentType != null && contentType.equalsIgnoreCase(CONTENT_TYPE)) {
        parameters = URLEncodedUtils.parse(entity);
    } else {
        final String content = EntityUtils.toString(entity, HTTP.ASCII);
        if (content != null && content.length() > 0) {
            parameters = new ArrayList<NameValuePair>();
            URLEncodedUtils.parse(parameters, new Scanner(content), charset);
        }
    }

    final Map<String, String> map = new HashMap<String, String>();
    for (final NameValuePair parameter : parameters) {
        map.put(parameter.getName(), parameter.getValue());
    }
    return map;
}

From source file:org.github.oauth2.AccessTokenClient.java

/**
 * Get token from resposne entity//from   w  w w.  ja  v a  2s . c  o  m
 * 
 * @param entity
 * @return token or null if not present in given entity
 * @throws IOException
 */
protected String getToken(HttpEntity entity) throws IOException {
    String content = EntityUtils.toString(entity, HTTP.ASCII);
    if (content == null || content.length() == 0)
        return null;
    List<NameValuePair> responseData = new ArrayList<NameValuePair>();
    URLEncodedUtils.parse(responseData, new Scanner(content), null);
    for (NameValuePair param : responseData)
        if (IOAuth2Constants.PARAM_ACCESS_TOKEN.equals(param.getName())) {
            String token = param.getValue();
            if (token != null && token.length() > 0)
                return token;
        }
    return null;
}

From source file:com.yoavst.quickapps.URLEncodedUtils.java

/**
 * Returns a list of {@link NameValuePair NameValuePairs} as parsed from an
 * {@link HttpEntity}. The encoding is taken from the entity's
 * Content-Encoding header.//  ww  w.j a  va 2  s.  co  m
 * <p/>
 * This is typically used while parsing an HTTP POST.
 *
 * @param entity The entity to parse
 * @throws IOException If there was an exception getting the entity's data.
 */
public static List<NameValuePair> parse(final HttpEntity entity) throws IOException {
    List<NameValuePair> result = Collections.emptyList();
    String contentType = null;
    String charset = null;
    Header h = entity.getContentType();
    if (h != null) {
        HeaderElement[] elems = h.getElements();
        if (elems.length > 0) {
            HeaderElement elem = elems[0];
            contentType = elem.getName();
            NameValuePair param = elem.getParameterByName("charset");
            if (param != null) {
                charset = param.getValue();
            }
        }
    }
    if (contentType != null && contentType.equalsIgnoreCase(CONTENT_TYPE)) {
        final String content = EntityUtils.toString(entity, HTTP.ASCII);
        if (content != null && content.length() > 0) {
            result = new ArrayList<>();
            parse(result, new Scanner(content), charset);
        }
    }
    return result;
}

From source file:gov.nasa.arc.geocam.memo.service.SiteAuthCookieImplementation.java

@Override
public int post(String relativePath, Map<String, String> params)
        throws AuthenticationFailedException, IOException, ClientProtocolException {
    ensureAuthenticated();//  w w  w  .j  av a 2s .  c o  m

    httpClient = new DefaultHttpClient();
    HttpParams httpParams = httpClient.getParams();
    HttpClientParams.setRedirecting(httpParams, false);
    httpParams.setParameter("http.protocol.handle-redirects", false);

    HttpPost post = new HttpPost(this.serverRootUrl + "/" + appPath + "/" + relativePath);
    post.setParams(httpParams);

    if (params != null) {
        List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
        for (String key : params.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
        }

        post.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.ASCII));
    }

    httpClient.getCookieStore().addCookie(sessionIdCookie);
    //post.setHeader("Cookie", sessionIdCookie.toString());

    HttpResponse r = httpClient.execute(post);
    // TODO: check for redirect to login and call login if is the case

    return r.getStatusLine().getStatusCode();
}

From source file:org.vietspider.net.apache.AbstractSessionInputBuffer.java

protected void init(final InputStream _instream, int buffersize, final HttpParams params) {
    if (_instream == null) {
        throw new IllegalArgumentException("Input stream may not be null");
    }//www . j av a 2 s .c  om
    if (buffersize <= 0) {
        throw new IllegalArgumentException("Buffer size may not be negative or zero");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    this.instream = _instream;
    this.buffer = new byte[buffersize];
    this.bufferpos = 0;
    this.bufferlen = 0;
    this.linebuffer = new ByteArrayBuffer(buffersize);
    this.charset = HttpProtocolParams.getHttpElementCharset(params);
    //    this.timeoutSocket = params.getBooleanParameter("vietspider.socket.timeout", false);
    this.ascii = this.charset.equalsIgnoreCase(HTTP.US_ASCII) || this.charset.equalsIgnoreCase(HTTP.ASCII);
    this.maxLineLen = params.getIntParameter(CoreConnectionPNames.MAX_LINE_LENGTH, -1);
    this.metrics = new HttpTransportMetricsImpl();
}

From source file:gov.nasa.arc.geocam.talk.service.SiteAuthCookie.java

@Override
public ServerResponse post(String relativePath, Map<String, String> params, byte[] audioBytes)
        throws AuthenticationFailedException, IOException, ClientProtocolException, InvalidParameterException {
    if (params == null) {
        throw new InvalidParameterException("Post parameters are required");
    }//from w  ww.  j a  v  a2 s .c o  m

    ensureAuthenticated();

    httpClient = new DefaultHttpClient();

    HttpParams httpParams = httpClient.getParams();
    HttpClientParams.setRedirecting(httpParams, false);

    HttpPost post = new HttpPost(this.serverRootUrl + "/" + appPath + "/" + relativePath);
    post.setParams(httpParams);

    HttpEntity httpEntity;

    if (audioBytes != null) {
        httpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        for (String key : params.keySet()) {
            ((MultipartEntity) httpEntity).addPart(key, new StringBody(params.get(key)));
        }
        if (audioBytes != null) {
            ((MultipartEntity) httpEntity).addPart("audio",
                    new ByteArrayBody(audioBytes, "audio/mpeg", "audio.mp4"));
        }
    } else {
        List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();

        for (String key : params.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
        }

        httpEntity = new UrlEncodedFormEntity(nameValuePairs, HTTP.ASCII);
    }

    post.setEntity(httpEntity);
    httpClient.getCookieStore().addCookie(sessionIdCookie);
    ServerResponse sr = new ServerResponse(httpClient.execute(post));

    if (sr.getResponseCode() == 401 || sr.getResponseCode() == 403) {
        throw new AuthenticationFailedException("Server responded with code: " + sr.getResponseCode());
    }

    return sr;
}

From source file:gov.nasa.arc.geocam.memo.service.SiteAuthCookieImplementation.java

/**
 * Login.//from   ww  w  .j  a v  a 2s  .co m
 *
 * @throws ClientProtocolException the client protocol exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws AuthenticationFailedException the authentication failed exception
 */
private void login() throws ClientProtocolException, IOException, AuthenticationFailedException {
    httpClient = new DefaultHttpClient();
    HttpParams params = httpClient.getParams();
    HttpClientParams.setRedirecting(params, false);

    Log.i("Talk", "Username:" + username);

    HttpPost p = new HttpPost(serverRootUrl + "/accounts/login/");
    p.setParams(params);

    List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("username", username));
    nameValuePairs.add(new BasicNameValuePair("password", password));

    p.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.ASCII));

    HttpResponse r = httpClient.execute(p);
    if (302 == r.getStatusLine().getStatusCode()) {
        for (Cookie c : httpClient.getCookieStore().getCookies()) {
            if (c.getName().contains("sessionid")) {
                sessionIdCookie = c;
                return;
            }
        }
        throw new AuthenticationFailedException("Session cookie was missing from server login response.");
    } else {
        throw new AuthenticationFailedException(
                "Got unexpected response code from server: " + r.getStatusLine().getStatusCode());
    }
}

From source file:gov.nasa.arc.geocam.talk.service.SiteAuthCookie.java

@Override
public void login() throws ClientProtocolException, IOException, AuthenticationFailedException {

    username = sharedPreferences.getString("username", null);
    password = sharedPreferences.getString("password", null);

    httpClient = new DefaultHttpClient();
    HttpParams params = httpClient.getParams();
    HttpClientParams.setRedirecting(params, false);

    HttpPost p = new HttpPost(serverRootUrl + "/accounts/login/");
    p.setParams(params);//  w  w  w.  ja  v  a  2 s  . c  o  m

    List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("username", username));
    nameValuePairs.add(new BasicNameValuePair("password", password));

    p.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.ASCII));

    HttpResponse r = httpClient.execute(p);
    if (302 == r.getStatusLine().getStatusCode()) {
        for (Cookie c : httpClient.getCookieStore().getCookies()) {
            if (c.getName().contains("sessionid")) {
                sessionIdCookie = c;
                intentHelper.RegisterC2dm();
                return;
            }
        }
        throw new AuthenticationFailedException("Session cookie was missing from server login response.");
    } else {
        throw new AuthenticationFailedException(
                "Got unexpected response code from server: " + r.getStatusLine().getStatusCode());
    }
}

From source file:gov.nasa.arc.geocam.talk.service.SiteAuthCookie.java

@Override
public void logoutAndUnregister() throws AuthenticationFailedException, ClientProtocolException, IOException {
    httpClient = new DefaultHttpClient();

    HttpGet g = new HttpGet(serverRootUrl + "/" + appPath + "/" + "unregister");
    httpClient.execute(g);//from  w  ww  .ja va2s .  c o  m

    httpClient = new DefaultHttpClient();

    HttpParams params = httpClient.getParams();
    HttpClientParams.setRedirecting(params, false);

    HttpPost p = new HttpPost(serverRootUrl + "/accounts/logout/");
    p.setParams(params);

    List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("username", username));
    nameValuePairs.add(new BasicNameValuePair("password", password));

    p.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.ASCII));

    HttpResponse r = httpClient.execute(p);

    sharedPreferences.edit().remove("username").commit();
    sharedPreferences.edit().remove("password").commit();

    if (302 == r.getStatusLine().getStatusCode()) {
        sessionIdCookie = null;
        return;
    } else {
        throw new AuthenticationFailedException(
                "Got unexpected response code from server: " + r.getStatusLine().getStatusCode());
    }
}

From source file:org.apache.http.localserver.RequestBasicAuth.java

public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {

    String auth = null;// w  ww.  j  a v a2s  .  c o  m

    Header h = request.getFirstHeader(AUTH.WWW_AUTH_RESP);
    if (h != null) {
        String s = h.getValue();
        if (s != null) {
            auth = s.trim();
        }
    }

    if (auth != null) {
        int i = auth.indexOf(' ');
        if (i == -1) {
            throw new ProtocolException("Invalid Authorization header: " + auth);
        }
        String authscheme = auth.substring(0, i);
        if (authscheme.equalsIgnoreCase("basic")) {
            String s = auth.substring(i + 1).trim();
            byte[] credsRaw = s.getBytes(HTTP.ASCII);
            BinaryDecoder codec = new Base64();
            try {
                String creds = new String(codec.decode(credsRaw), HTTP.ASCII);
                context.setAttribute("creds", creds);
            } catch (DecoderException ex) {
                throw new ProtocolException("Malformed BASIC credentials");
            }
        }
    }
}