Example usage for org.apache.http.client.utils URIUtils createURI

List of usage examples for org.apache.http.client.utils URIUtils createURI

Introduction

In this page you can find the example usage for org.apache.http.client.utils URIUtils createURI.

Prototype

@Deprecated
public static URI createURI(final String scheme, final String host, final int port, final String path,
        final String query, final String fragment) throws URISyntaxException 

Source Link

Document

Constructs a URI using all the parameters.

Usage

From source file:gtu.youtube.JavaYoutubeDownloader.java

private URI getUri(String path, List<NameValuePair> qparams) throws URISyntaxException {
    URI uri = URIUtils.createURI(scheme, host, -1, "/" + path,
            URLEncodedUtils.format(qparams, DEFAULT_ENCODING), null);
    System.out.println("getUri = " + uri);
    return uri;/*w ww  . j a v  a  2  s  .  c o m*/
}

From source file:mobisocial.musubi.identity.AphidIdentityProvider.java

private JSONObject getAphidResult(JSONArray userinfo) throws IOException {
    // Set up HTTP request
    HttpClient http = new CertifiedHttpClient(mContext);
    URI uri;//from   w w w  .  ja v  a2s  .c o m
    try {
        uri = URIUtils.createURI(URL_SCHEME, SERVER_LOCATION, -1, KEYS_PATH, null, null);
    } catch (URISyntaxException e) {
        throw new IOException("Malformed URL", e);
    }
    HttpPost post = new HttpPost(uri);
    List<NameValuePair> postData = new ArrayList<NameValuePair>();
    postData.add(new BasicNameValuePair("userinfo", userinfo.toString()));
    Log.d(TAG, "Server request: " + userinfo.toString());

    // Send the request
    post.setEntity(new UrlEncodedFormEntity(postData, HTTP.UTF_8));
    HttpResponse response = http.execute(post);

    // Read the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String responseStr = "";
    String line = "";
    while ((line = rd.readLine()) != null) {
        responseStr += line;
    }
    Log.d(TAG, "Server response:" + responseStr);

    // Parse the response as JSON
    try {
        JSONArray arr = new JSONArray(responseStr);
        if (arr.length() != 0) {
            JSONObject object = arr.getJSONObject(0);
            return object;
        } else {
            return null;
        }
    } catch (JSONException e) {
        throw new IOException("Bad JSON format", e);
    }
}

From source file:org.craftercms.social.UCGRestServicesTest.java

public static void main(String[] args) throws Exception {

    ProfileClient profileRestClient = new ProfileRestClientImpl();

    String token = profileRestClient.getAppToken("craftersocial", "craftersocial");
    Tenant tenant = profileRestClient.getTenantByName(token, "testing");
    String ticket = profileRestClient.getTicket(token, "admin", "admin", tenant.getId());
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("ticket", ticket));
    qparams.add(new BasicNameValuePair("target", "testing"));

    qparams.add(new BasicNameValuePair("textContent", "Content"));

    URI uri = URIUtils.createURI("http", "localhost", 8080, "crafter-social/api/1/ugc/" + "create.json",
            URLEncodedUtils.format(qparams, HTTP.UTF_8), null);

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(uri);
    File file = new File(
            "/Users/alvarogonzalez/development/projects/crafter-social/rest/src/test/resources/test.txt");
    MultipartEntity me = new MultipartEntity();

    //The usual form parameters can be added this way
    //me.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : "")) ;
    //multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName())) ;

    /*Need to construct a FileBody with the file that needs to be attached and specify the mime type of the file. Add the fileBody to the request as an another part.
    This part will be considered as file part and the rest of them as usual form-data parts*/
    FileBody fileBody = new FileBody(file, "application/octect-stream");
    //me.addPart("ticket", new StringBody(token)) ;
    //me.addPart("target", new StringBody("my-test")) ;
    me.addPart("attachments", fileBody);

    httppost.setEntity(me);/*ww  w.  j  a  va2s  . co  m*/
    httpclient.execute(httppost);

}

From source file:com.healthcit.cacure.dao.CouchDBDao.java

/**
 * Query for answers for a list(Collection) of questions
 * @param ownerId//from   w  ww.jav a 2 s .  co  m
 * @param questionIDs - Collection of questions
 * @return map (key = formId_questionId, values - related answers)
 * @throws IOException
 * @throws URISyntaxException
 */
@SuppressWarnings("unchecked")
public List<AnswerSearchResultsBean> getAnswersByOwnerAndQuestion(String ownerId,
        Collection<AnswerSearchCriteriaBean> criterias) throws IOException, URISyntaxException {
    // construct query body
    /* SAMPLE JSON BODY for this query:
       {
    "keys":[
       ["88cdceae-6311-4994-ae4d-8e071b59b7b1","7e11e7b6-df8e-4787-a3e6-2c8b4a3cef52"],
       ["6e086702-e0b9-4b5f-9304-8c01dd280380","8a3d1587-f170-41ea-8b4d-e0c6e00aaefe"]
    ]
       }
    */
    JSONObject jsonBody = new JSONObject();
    JSONArray keys = new JSONArray();

    for (AnswerSearchCriteriaBean criteria : criterias) {
        JSONArray aKey = new JSONArray();
        aKey.add(ownerId);
        aKey.add(criteria.getFormId());
        if (criteria.getRowId() != null) {
            aKey.add(criteria.getRowId());
        }
        aKey.add(criteria.getQuestionId());
        keys.add(aKey);
    }
    jsonBody.put("keys", keys);

    // send it
    URI uri = URIUtils.createURI("http", host, port, constructViewURL("GetAnswersByOwnerAndQuestion"), null,
            null);

    String response = runPostQuery(uri, jsonBody.toString());

    log.debug("In getAnswersByOwnerAndQuestion: response:");
    log.debug("==================");
    log.debug(response);

    // parse response
    ArrayList<AnswerSearchResultsBean> results = new ArrayList<AnswerSearchResultsBean>();
    JSONObject jsonData = (JSONObject) JSONSerializer.toJSON(response);
    // must contain an array of values
    if (jsonData.containsKey("rows")) {
        JSONArray resultSet = jsonData.getJSONArray("rows");
        Iterator<JSONObject> rowIter = resultSet.iterator();
        while (rowIter.hasNext()) {
            JSONObject row = rowIter.next();
            JSONArray values = row.getJSONArray("value");
            Collection<String> javaValues = JSONArray.toCollection(values);
            JSONArray key = row.getJSONArray("key");
            AnswerSearchCriteriaBean criteria = new AnswerSearchCriteriaBean();
            criteria.setFormId(key.getString(1));
            criteria.setRowId(key.size() >= 4 ? key.getString(2) : null);
            criteria.setQuestionId(key.size() >= 4 ? key.getString(3) : key.getString(2));
            results.add(new AnswerSearchResultsBean(criteria, javaValues));
        }
    }
    return results;
}

From source file:org.b3log.latke.client.LatkeClient.java

/**
 * Gets repository names./*w  w  w  .ja  v  a  2  s  .  c o m*/
 * 
 * @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;
}

From source file:org.opendatakit.dwc.server.GreetingServiceImpl.java

@Override
public String obtainOauth2Code(String destinationUrl) throws IllegalArgumentException {
    URI nakedUri;/*from  w  w w  .  ja  va 2 s  . c om*/
    try {
        nakedUri = new URI(authUrl);
    } catch (URISyntaxException e2) {
        e2.printStackTrace();
        logger.error(e2.toString());
        return getSelfUrl();
    }
    addCredentials(CLIENT_ID, CLIENT_SECRET, nakedUri.getHost());
    Context ctxt = new Context();
    stateMap.put(ctxt.getKey(), ctxt);
    ctxtKey = ctxt.getKey();

    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("response_type", "code"));
    qparams.add(new BasicNameValuePair("client_id", CLIENT_ID));
    qparams.add(new BasicNameValuePair("scope", scope));
    qparams.add(new BasicNameValuePair("redirect_uri", getOauth2CallbackUrl()));
    qparams.add(new BasicNameValuePair("state", ctxt.getKey()));
    URI uri;
    try {
        uri = URIUtils.createURI(nakedUri.getScheme(), nakedUri.getHost(), nakedUri.getPort(),
                nakedUri.getPath(), URLEncodedUtils.format(qparams, "UTF-8"), null);
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
        logger.error(e1.toString());
        return getSelfUrl();
    }

    String toString = uri.toString();
    return toString;
}

From source file:edu.rit.csh.androidwebnews.HttpsConnector.java

/**
 * Formats the URL String with the API key and all the extra parameters for GET requests
 *
 * @param addOn  - the add on to the url to format
 * @param addOns - List<NameValuePair> of extra parameters, can be empty
 * @return String - the formated String//from   www  .ja  v a  2s.c o  m
 */
private URI formatUrl(String addOn, HashMap<String, String> addOns) {
    //if (!url.endsWith("?")) {
    //   url += "?";
    //}
    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("api_key", sharedPref.getString("api_key", "")));
    params.add(new BasicNameValuePair("api_agent", "Android_Webnews"));
    if (addOns != null) {
        for (String key : addOns.keySet()) {
            params.add(new BasicNameValuePair(key, addOns.get(key)));
        }
    }
    try {
        return URIUtils.createURI("https", "webnews.csh.rit.edu", -1, "/" + addOn,
                URLEncodedUtils.format(params, "UTF-8"), null);
    } catch (URISyntaxException e) {
        return null;
    }
}

From source file:com.naryx.tagfusion.cfm.http.cfHttpConnection.java

private void addQueryStringData(Map<String, String> _data, String _charset) throws cfmRunTimeException {

    if (_data.size() > 0) { // don't need to do anything if there's no url data
                            // to add
        StringBuilder queryString = new StringBuilder(); // method.getQueryString()
                                                         // );
        Iterator<String> keys = _data.keySet().iterator();
        while (keys.hasNext()) {
            String nextKey = keys.next();
            try {
                queryString.append(urlEncoder.encode(nextKey, _charset));
            } catch (UnsupportedEncodingException e1) {
                queryString.append(urlEncoder.encode(nextKey));
            }//  w ww . j ava2s .  c om
            queryString.append('=');
            try {
                queryString.append(urlEncoder.encode(_data.get(nextKey), _charset));
            } catch (UnsupportedEncodingException e) {
                queryString.append(urlEncoder.encode(_data.get(nextKey)));
            }
            queryString.append("&");
        }
        // remove last &. We know there is at least one url param
        queryString = queryString.deleteCharAt(queryString.length() - 1);
        String currentQStr = message.getURI().getQuery();
        if (currentQStr == null)
            currentQStr = "";
        try {
            URI uri = message.getURI();
            String schemeName = uri.getScheme();
            String hostName = uri.getHost();
            int port = uri.getPort();
            String fragment = uri.getFragment();
            String path = uri.getPath();
            String queryStr = queryString.toString();

            if (currentQStr.length() > 0) {
                uri = URIUtils.createURI(schemeName, hostName, port, path, currentQStr + '&' + queryStr,
                        fragment);
            } else {
                uri = URIUtils.createURI(schemeName, hostName, port, path, queryStr, fragment);
            }

            ((HttpRequestBase) message).setURI(uri);

        } catch (URISyntaxException e) {
            throw newRunTimeException("Failed due to URI Syntax Error: " + e.getMessage());
        }

    }

}

From source file:com.healthcit.cacure.dao.CouchDBDao.java

/**
 * Query for answers for a list(Collection) of questions
 * @param ownerId//  ww  w . ja v  a  2  s .  c  o  m
 * @param questionIDs - Collection of questions
 * @return map (key = formId_questionId, values - related answers)
 * @throws IOException
 * @throws URISyntaxException
 */
@SuppressWarnings("unchecked")
public JSONObject getLatestAnswersByOwnerAndQuestion(String ownerId, List<String> questionIds)
        throws IOException, URISyntaxException {
    // construct query body
    /* SAMPLE JSON BODY for this query:
       {
    "keys":[
       ["88cdceae-6311-4994-ae4d-8e071b59b7b1","7e11e7b6-df8e-4787-a3e6-2c8b4a3cef52"],
       ["6e086702-e0b9-4b5f-9304-8c01dd280380","8a3d1587-f170-41ea-8b4d-e0c6e00aaefe"]
    ]
       }
    */
    JSONObject jsonBody = new JSONObject();
    JSONArray keys = new JSONArray();

    for (String questionId : questionIds) {
        JSONArray aKey = new JSONArray();
        aKey.add(ownerId);
        aKey.add(questionId);
        keys.add(aKey);
    }
    jsonBody.put("keys", keys);
    //      jsonBody.put("group", "true");

    // send it
    URI uri = URIUtils.createURI("http", host, port, constructViewURL("GetLatestAnswersByOwnerAndQuestion"),
            null, null);

    String response = runPostQuery(uri, jsonBody.toString());

    log.debug("In getLatestAnswersByOwnerAndQuestion: response:");
    log.debug("==================");
    log.debug(response);

    //      // parse response
    ArrayList<AnswerSearchResultsBean> results = new ArrayList<AnswerSearchResultsBean>();
    JSONObject jsonData = (JSONObject) JSONSerializer.toJSON(response);
    //      // must contain an array of values
    //      if ( jsonData.containsKey("rows")){
    //         JSONArray resultSet = jsonData.getJSONArray("rows");
    //         Iterator<JSONObject> rowIter = resultSet.iterator();
    //         while (rowIter.hasNext())
    //         {
    //            JSONObject row = rowIter.next();
    //            JSONArray values = row.getJSONArray("value");
    //            Collection<String> javaValues = JSONArray.toCollection(values);
    //            JSONArray key = row.getJSONArray("key");
    //            AnswerSearchCriteriaBean criteria = new AnswerSearchCriteriaBean();
    //            criteria.setFormId(key.getString(1));
    //            criteria.setRowId(key.size() >= 4 ? key.getString(2) : null);
    //            criteria.setQuestionId(key.size() >= 4 ? key.getString(3) : key.getString(2));
    //            results.add(new AnswerSearchResultsBean(criteria, javaValues));
    //         }
    //      }
    return jsonData;

}