Java Code Examples for org.apache.http.client.utils.URLEncodedUtils#format()

The following examples show how to use org.apache.http.client.utils.URLEncodedUtils#format() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpParamDelegationTokenPlugin.java    From lucene-solr with Apache License 2.0 9 votes vote down vote up
@Override
protected void doFilter(FilterChain filterChain, HttpServletRequest request,
                        HttpServletResponse response) throws IOException, ServletException {
  // remove the filter-specific authentication information, so it doesn't get accidentally forwarded.
  List<NameValuePair> newPairs = new LinkedList<NameValuePair>();
  List<NameValuePair> pairs = URLEncodedUtils.parse(request.getQueryString(), Charset.forName("UTF-8"));
  for (NameValuePair nvp : pairs) {
    if (!USER_PARAM.equals(nvp.getName())) {
      newPairs.add(nvp);
    }
    else {
      request.setAttribute(USER_PARAM, nvp.getValue());
    }
  }
  final String queryStringNoUser = URLEncodedUtils.format(newPairs, StandardCharsets.UTF_8);
  HttpServletRequest requestWrapper = new HttpServletRequestWrapper(request) {
    @Override
    public String getQueryString() {
      return queryStringNoUser;
    }
  };
  super.doFilter(filterChain, requestWrapper, response);
}
 
Example 2
Source File: HttpUtils.java    From we-cmdb with Apache License 2.0 6 votes vote down vote up
/**
 * get请求
 *
 * @param msgs
 * @param url
 * @return
 * @throws ClientProtocolException
 * @throws UnknownHostException
 * @throws IOException
 */
public static String get(Map<String, Object> msgs, String url)
        throws ClientProtocolException, UnknownHostException, IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        List<NameValuePair> valuePairs = new ArrayList<NameValuePair>();
        if (null != msgs) {
            for (Entry<String, Object> entry : msgs.entrySet()) {
                if (entry.getValue() != null) {
                    valuePairs.add(new BasicNameValuePair(entry.getKey(),
                            entry.getValue().toString()));
                }
            }
        }
        // EntityUtils.toString(new UrlEncodedFormEntity(valuePairs),
        // CHARSET);
        url = url + "?" + URLEncodedUtils.format(valuePairs, CHARSET_UTF_8);
        HttpGet request = new HttpGet(url);
        CloseableHttpResponse resp = httpClient.execute(request);
        return EntityUtils.toString(resp.getEntity(), CHARSET_UTF_8);
    } finally {
        httpClient.close();
    }
}
 
Example 3
Source File: HwYunMsgSender.java    From WePush with MIT License 6 votes vote down vote up
/**
 * 构造请求Body体
 *
 * @param sender
 * @param receiver
 * @param templateId
 * @param templateParas
 * @param statusCallbackUrl
 * @param signature         | 签名名称,使用国内短信通用模板时填写
 * @return
 */
static String buildRequestBody(String sender, String receiver, String templateId, String templateParas,
                               String statusCallbackUrl, String signature) {
    if (null == sender || null == receiver || null == templateId || sender.isEmpty() || receiver.isEmpty()
            || templateId.isEmpty()) {
        System.out.println("buildRequestBody(): sender, receiver or templateId is null.");
        return null;
    }
    List<NameValuePair> keyValues = new ArrayList<>();

    keyValues.add(new BasicNameValuePair("from", sender));
    keyValues.add(new BasicNameValuePair("to", receiver));
    keyValues.add(new BasicNameValuePair("templateId", templateId));
    if (null != templateParas && !templateParas.isEmpty()) {
        keyValues.add(new BasicNameValuePair("templateParas", templateParas));
    }
    if (null != statusCallbackUrl && !statusCallbackUrl.isEmpty()) {
        keyValues.add(new BasicNameValuePair("statusCallback", statusCallbackUrl));
    }
    if (null != signature && !signature.isEmpty()) {
        keyValues.add(new BasicNameValuePair("signature", signature));
    }

    return URLEncodedUtils.format(keyValues, Charset.forName("UTF-8"));
}
 
Example 4
Source File: GitLabSecurityRealm.java    From gitlab-oauth-plugin with MIT License 6 votes vote down vote up
public HttpResponse doCommenceLogin(StaplerRequest request, @QueryParameter String from, @Header("Referer") final String referer) throws IOException {
    // 2. Requesting authorization :
    // http://doc.gitlab.com/ce/api/oauth2.html

    String redirectOnFinish;
    if (from != null && Util.isSafeToRedirectTo(from)) {
        redirectOnFinish = from;
    } else if (referer != null && (referer.startsWith(Jenkins.getInstance().getRootUrl()) || Util.isSafeToRedirectTo(referer))) {
        redirectOnFinish = referer;
    } else {
        redirectOnFinish = Jenkins.getInstance().getRootUrl();
    }

    List<NameValuePair> parameters = new ArrayList<>();
    parameters.add(new BasicNameValuePair("redirect_uri", buildRedirectUrl(request, redirectOnFinish)));
    parameters.add(new BasicNameValuePair("response_type", "code"));
    parameters.add(new BasicNameValuePair("client_id", clientID));

    return new HttpRedirect(gitlabWebUri + "/oauth/authorize?" + URLEncodedUtils.format(parameters, StandardCharsets.UTF_8));
}
 
Example 5
Source File: HarborClient.java    From harbor-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * Let user see the recent operation logs of the projects which he is member
 * of.</br>
 * <b>URL</b>: /logs</br>
 * <b>Method</b>: GET
 *
 * @param lines
 *            (The number of logs to be shown, default is 10 if lines,
 *            start_time, end_time are not provided)
 * @param startTime
 *            (The start time of logs to be shown in unix timestap)
 * @param endTime
 *            (The end time of logs to be shown in unix timestap)
 * @return required logs.
 * @throws IOException
 * @throws HarborClientException
 */
public List<Log> getLogs(String lines, String startTime, String endTime) throws IOException, HarborClientException {
	logger.debug("get logs lines %s, start time %s, end time %s", lines, startTime, endTime);
	List<NameValuePair> qparams = new ArrayList<>();
	qparams.add(new BasicNameValuePair("lines", lines));
	qparams.add(new BasicNameValuePair("start_time", startTime));
	qparams.add(new BasicNameValuePair("end_time", endTime));
	qparams.removeIf(o -> Objects.isNull(o.getValue()));
	String url = getBaseUrl() + "/logs?" + URLEncodedUtils.format(qparams, "UTF-8");
	Request request = new Request.Builder().url(url).get().build();
	Response response = okhttpClient.newCall(request).execute();
	logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response));
	if (response.code() != 200) {
		throw new HarborClientException(String.valueOf(response.code()), response.message());
	}
	return mapper.readValue(response.body().string(), new TypeReference<List<Log>>() {
	});
}
 
Example 6
Source File: HarborClient.java    From harbor-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * This endpoint returns all projects created by Harbor, and can be filtered
 * by project name.</br>
 * <b>URL</b>: /projects</br>
 * <b>Method</b>: GET
 *
 * @param projectName
 *            (Project name for filtering results)
 * @param isPublic
 *            (Public sign for filtering projects)
 * @return
 * @throws IOException
 * @throws HarborClientException
 */
public List<Project> getProjects(String projectName, String isPublic) throws IOException, HarborClientException {
	List<NameValuePair> qparams = new ArrayList<>();
	qparams.add(new BasicNameValuePair("project_name", projectName));
	qparams.add(new BasicNameValuePair("is_public", isPublic));
	qparams.removeIf(o -> Objects.isNull(o.getValue()));
	String url = getBaseUrl() + "projects?" + URLEncodedUtils.format(qparams, "UTF-8");
	Request request = new Request.Builder().url(url).get().build();
	Response response = okhttpClient.newCall(request).execute();
	logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response));
	if (response.code() != 200) {
		throw new HarborClientException(String.valueOf(response.code()), response.message());
	}
	return mapper.readValue(response.body().string(), new TypeReference<List<Project>>() {
	});
}
 
Example 7
Source File: Application.java    From dr-elephant with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the request for the queryString
 *
 * @return URL Encoded String of Parameter Value Pair
 */
public static String getQueryString() {
  List<BasicNameValuePair> fields = new LinkedList<BasicNameValuePair>();
  final Set<Map.Entry<String, String[]>> entries = request().queryString().entrySet();
  for (Map.Entry<String, String[]> entry : entries) {
    final String key = entry.getKey();
    final String value = entry.getValue()[0];
    if (!key.equals(PAGE)) {
      fields.add(new BasicNameValuePair(key, value));
    }
  }
  if (fields.isEmpty()) {
    return null;
  } else {
    return URLEncodedUtils.format(fields, "utf-8");
  }
}
 
Example 8
Source File: SolrSearcher.java    From q with Apache License 2.0 6 votes vote down vote up
public String getUrlForGettingDoc(String q, List<String> languages, String dataSetId)
{
	List<NameValuePair> parameters = Lists.newArrayList();

	parameters.add(new BasicNameValuePair("q", getPhraseQueryString(q)));
	parameters.add(new BasicNameValuePair("defType", "edismax"));
	parameters.add(new BasicNameValuePair("lowercaseOperators", "false"));
	parameters.add(new BasicNameValuePair("rows", "100000"));
	parameters.add(new BasicNameValuePair("qs", "10"));
	parameters.add(new BasicNameValuePair("fl", Properties.idField.get() + ", " + Properties.titleFields.get().get(0) + "_en"));
	parameters.add(new BasicNameValuePair("sort", Properties.idField.get() + " DESC"));
	parameters.add(new BasicNameValuePair("qf", getQueryFields(languages)));
	parameters.add(new BasicNameValuePair("fq", Properties.docTypeFieldName.get() + ":" + dataSetId));
	parameters.add(new BasicNameValuePair("wt", "json"));

	return getServerUrl() + "/select?" + URLEncodedUtils.format(parameters, BaseIndexer.ENCODING);
}
 
Example 9
Source File: HttpUtil.java    From anyline with Apache License 2.0 6 votes vote down vote up
public static HttpResult get(CloseableHttpClient client, Map<String, String> headers, String url, String encode, List<NameValuePair> pairs) { 
	if(null == client){ 
		if(url.contains("https://")){ 
			client = defaultSSLClient(); 
		}else{ 
			client =  defaultClient(); 
		} 
	} 
	if(url.startsWith("//")){ 
		url = "http:" + url; 
	} 
	HttpResult result = new HttpResult(); 
	if (null != pairs && !pairs.isEmpty()) { 
		String params = URLEncodedUtils.format(pairs,encode); 
		if (url.contains("?")) { 
			url += "&" + params; 
		} else { 
			url += "?" + params; 
		} 
	} 
	HttpGet method = new HttpGet(url); 
	setHeader(method, headers); 
	result = exe(client, method, encode); 
	return result; 
}
 
Example 10
Source File: HttpClients.java    From flash-waimai with MIT License 5 votes vote down vote up
/**
 * 封装HTTP GET方法
 *
 * @param
 * @param
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
public static String get(String url, Map<String, String> paramMap) throws ClientProtocolException, IOException {
	HttpClient httpClient = new DefaultHttpClient();
	HttpGet httpGet = new HttpGet();
	List<NameValuePair> formparams = setHttpParams(paramMap);
	String param = URLEncodedUtils.format(formparams, "UTF-8");
	httpGet.setURI(URI.create(url + "?" + param));
	HttpResponse response = httpClient.execute(httpGet);
	String httpEntityContent = getHttpEntityContent(response);
	httpGet.abort();
	return httpEntityContent;
}
 
Example 11
Source File: HttpClients.java    From flash-waimai with MIT License 5 votes vote down vote up
/**
 * 封装HTTP DELETE方法
 *
 * @param
 * @param
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
public static String delete(String url, Map<String, String> paramMap) throws ClientProtocolException, IOException {
	HttpClient httpClient = new DefaultHttpClient();
	HttpDelete httpDelete = new HttpDelete();
	List<NameValuePair> formparams = setHttpParams(paramMap);
	String param = URLEncodedUtils.format(formparams, "UTF-8");
	httpDelete.setURI(URI.create(url + "?" + param));
	HttpResponse response = httpClient.execute(httpDelete);
	String httpEntityContent = getHttpEntityContent(response);
	httpDelete.abort();
	return httpEntityContent;
}
 
Example 12
Source File: ESchoolParser.java    From substitution-schedule-parser with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public SubstitutionSchedule getSubstitutionSchedule()
        throws IOException, JSONException, CredentialInvalidException {
    if (!(scheduleData.getAuthenticationData() instanceof NoAuthenticationData)
            && (credential == null || !(credential instanceof PasswordCredential)
            || ((PasswordCredential) credential).getPassword() == null
            || ((PasswordCredential) credential).getPassword().isEmpty())) {
        throw new IOException("no login");
    }

    List<NameValuePair> nvps = new ArrayList<>();
    nvps.add(new BasicNameValuePair("wp", scheduleData.getData().getString(PARAM_ID)));
    nvps.add(new BasicNameValuePair("go", "vplan"));
    nvps.add(new BasicNameValuePair("content", "x14"));
    nvps.add(new BasicNameValuePair("sortby", "S"));

    String url = BASE_URL + "?" + URLEncodedUtils.format(nvps, "UTF-8");

    Document doc = Jsoup.parse(httpGet(url, ENCODING));
    if (doc.select("form[name=loginform]").size() > 0
            && scheduleData.getAuthenticationData() instanceof PasswordAuthenticationData) {
        // Login required
        List<NameValuePair> formParams = new ArrayList<>();
        formParams.add(new BasicNameValuePair("password", ((PasswordCredential) credential).getPassword()));
        formParams.add(new BasicNameValuePair("login", ""));
        doc = Jsoup.parse(httpPost(url, ENCODING, formParams));

        if (doc.select("font[color=red]").text().contains("fehlgeschlagen")) {
            throw new CredentialInvalidException();
        }
    }

    SubstitutionSchedule schedule = parseESchoolSchedule(doc);

    return schedule;
}
 
Example 13
Source File: HttpRestWb.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void listDocuments(CloseableHttpClient httpclient, long parentId) throws ClientProtocolException, IOException {

		System.out.println("listDocuments");

		List<NameValuePair> params = new LinkedList<NameValuePair>();
		params.add(new BasicNameValuePair("folderId", String.valueOf(parentId)));
		//params.add(new BasicNameValuePair("fileName", "gjhghjgj")); // this should result nothing
		//params.add(new BasicNameValuePair("fileName", "InvoiceProcessing01-workflow.png"));
		//params.add(new BasicNameValuePair("fileName", "*.png"));
		params.add(new BasicNameValuePair("fileName", "*"));

		StringBuilder requestUrl = new StringBuilder(BASE_PATH + "/services/rest/document/listDocuments");
		String querystring = URLEncodedUtils.format(params, "utf-8");
		requestUrl.append("?");
		requestUrl.append(querystring);

		System.out.println(requestUrl);

		//CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpGet method = new HttpGet(requestUrl.toString());
		method.setHeader("Accept", "application/json");

		CloseableHttpResponse response1 = httpclient.execute(method);

		try {
			System.out.println(response1.getStatusLine());
			HttpEntity entity2 = response1.getEntity();

			String respoBody = EntityUtils.toString(entity2, "UTF-8");
			System.out.println(respoBody);

			// do something useful with the response body
			// and ensure it is fully consumed
			EntityUtils.consume(entity2);
		} finally {
			response1.close();
		}
	}
 
Example 14
Source File: HttpRestWb.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void listChildren(CloseableHttpClient httpclient, long parentId) throws ClientProtocolException, IOException {

		//System.out.println("sid: " + httpclient);

		List<NameValuePair> params = new LinkedList<NameValuePair>();
		params.add(new BasicNameValuePair("folderId", String.valueOf(parentId)));

		StringBuilder requestUrl = new StringBuilder(BASE_PATH + "/services/rest/folder/listChildren");
		String querystring = URLEncodedUtils.format(params, "utf-8");
		requestUrl.append("?");
		requestUrl.append(querystring);

		System.out.println(requestUrl);

		//CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpGet method = new HttpGet(requestUrl.toString());
		method.setHeader("Accept", "application/json");

		CloseableHttpResponse response1 = httpclient.execute(method);

		try {
			System.out.println(response1.getStatusLine());
			HttpEntity entity2 = response1.getEntity();

			String respoBody = EntityUtils.toString(entity2, "UTF-8");
			System.out.println(respoBody);

			// do something useful with the response body
			// and ensure it is fully consumed
			EntityUtils.consume(entity2);
		} finally {
			response1.close();
		}
	}
 
Example 15
Source File: AwsSigner4.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private String getCanonicalQuery(URI uri) {
    String query = uri.getQuery();
    if(query == null || query.isEmpty()) {
        return "";
    }
    List<NameValuePair> params = URLEncodedUtils.parse(query, StandardCharsets.UTF_8);
    Collections.sort(params, new Comparator<NameValuePair>() {
        @Override
        public int compare(NameValuePair l, NameValuePair r) {
            return l.getName().compareToIgnoreCase(r.getName());
        }
    });
    return URLEncodedUtils.format(params, StandardCharsets.UTF_8);
}
 
Example 16
Source File: ApacheHttpUtils.java    From karate with MIT License 5 votes vote down vote up
public static HttpEntity getEntity(MultiValuedMap fields, String mediaType, Charset charset) {
    List<NameValuePair> list = new ArrayList<>(fields.size());
    for (Map.Entry<String, List> entry : fields.entrySet()) {
        String stringValue;
        List values = entry.getValue();
        if (values == null) {
            stringValue = null;
        } else if (values.size() == 1) {
            Object value = values.get(0);
            if (value == null) {
                stringValue = null;
            } else if (value instanceof String) {
                stringValue = (String) value;
            } else {
                stringValue = value.toString();
            }
        } else {
            stringValue = StringUtils.join(values, ',');
        }
        list.add(new BasicNameValuePair(entry.getKey(), stringValue));
    }
    try {
        Charset cs = HttpUtils.parseContentTypeCharset(mediaType);
        if (cs == null) {
            cs = charset;
        }            
        String raw = URLEncodedUtils.format(list, cs);
        int pos = mediaType.indexOf(';');
        if (pos != -1) { // strip out charset param from content-type
            mediaType = mediaType.substring(0, pos);
        }
        return new StringEntity(raw, ContentType.create(mediaType, cs));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 17
Source File: GitLabSecurityRealm.java    From gitlab-oauth-plugin with MIT License 5 votes vote down vote up
private String buildRedirectUrl(StaplerRequest request, String referer) throws MalformedURLException {
    URL currentUrl = new URL(Jenkins.getInstance().getRootUrl());
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("state", referer));

    URL redirect_uri = new URL(currentUrl.getProtocol(), currentUrl.getHost(), currentUrl.getPort(),
            request.getContextPath() + "/securityRealm/finishLogin?" + URLEncodedUtils.format(parameters, StandardCharsets.UTF_8));
    return redirect_uri.toString();
}
 
Example 18
Source File: HttpFluentService.java    From AthenaServing with Apache License 2.0 5 votes vote down vote up
private String buildGetParam(String url, Map<String, String> paramMap) {
    Args.notNull(url, "url");
    if(!paramMap.isEmpty()) {
        List<NameValuePair> paramList = Lists.newArrayListWithCapacity(paramMap.size());
        for (String key : paramMap.keySet()) {
            paramList.add(new BasicNameValuePair(key, paramMap.get(key)));
        }
        //拼接参数
        url += "?" + URLEncodedUtils.format(paramList, Consts.UTF_8);
    }
    return url;
}
 
Example 19
Source File: RequestParams.java    From letv with Apache License 2.0 4 votes vote down vote up
protected String getParamString() {
    return URLEncodedUtils.format(getParamsList(), ENCODING);
}
 
Example 20
Source File: YunpianApi.java    From yunpian-java-sdk with MIT License 2 votes vote down vote up
/**
 * 
 * @param param
 * @return 'application/x-www-form-urlencoded' format
 */
protected String urlEncode(List<NameValuePair> param) {
    if (param == null) return "";
    return URLEncodedUtils.format(param, charset());
}