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

The following are Jave code examples for showing how to use format() of the org.apache.http.client.utils.URLEncodedUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Equella   File: AbstractRestApiTest.java   View Source Code Vote up 7 votes
protected String paramString(Map<String, ?> paramMap)
{
	List<NameValuePair> params = Lists.newArrayList();
	if( paramMap != null )
	{
		for( Entry<String, ?> paramEntry : paramMap.entrySet() )
		{
			Object value = paramEntry.getValue();
			if( value != null )
			{
				params.add(new BasicNameValuePair(paramEntry.getKey(), value.toString()));
			}
		}
	}
	return URLEncodedUtils.format(params, "UTF-8");
}
 
Example 2
Project: incubator-servicecomb-java-chassis   File: AbstractTransport.java   View Source Code Vote up 6 votes
private String genAddressWithoutSchema(String addressWithoutSchema, Map<String, String> pairs) {
  if (addressWithoutSchema == null || pairs == null || pairs.isEmpty()) {
    return addressWithoutSchema;
  }

  int idx = addressWithoutSchema.indexOf('?');
  if (idx == -1) {
    addressWithoutSchema += "?";
  } else {
    addressWithoutSchema += "&";
  }

  String encodedQuery = URLEncodedUtils.format(pairs.entrySet().stream().map(entry -> {
    return new BasicNameValuePair(entry.getKey(), entry.getValue());
  }).collect(Collectors.toList()), StandardCharsets.UTF_8.name());

  if (!RegistryUtils.getServiceRegistry().getFeatures().isCanEncodeEndpoint()) {
    addressWithoutSchema = genAddressWithoutSchemaForOldSC(addressWithoutSchema, encodedQuery);
  } else {
    addressWithoutSchema += encodedQuery;
  }

  return addressWithoutSchema;
}
 
Example 3
Project: Equella   File: SearchApiTest.java   View Source Code Vote up 6 votes
private JsonNode doSearch(String info, String query, Map<?, ?> otherParams, String token) throws Exception
{
	List<NameValuePair> params = Lists.newArrayList();
	if( info != null )
	{
		params.add(new BasicNameValuePair("info", info));
	}
	if( query != null )
	{
		params.add(new BasicNameValuePair("q", query));
	}
	for( Entry<?, ?> entry : otherParams.entrySet() )
	{
		params.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString()));
	}
	// params.add(new BasicNameValuePair("token",
	// TokenSecurity.createSecureToken(username, "token", "token", null)));
	String paramString = URLEncodedUtils.format(params, "UTF-8");
	HttpGet get = new HttpGet(context.getBaseUrl() + "api/search?" + paramString);
	HttpResponse response = execute(get, false, token);
	return mapper.readTree(response.getEntity().getContent());
}
 
Example 4
Project: q   File: SolrSearcher.java   View Source Code Vote up 6 votes
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 5
Project: ApiDebugger   File: CommonUtil.java   View Source Code Vote up 6 votes
/**
     * 拼装Url与参数
     *
     * @param url
     * @param params
     * @return
     */
    public static String mergeUrlParams(@NotNull String url, HashMap<String, String> params) {
        if (params == null || params.isEmpty()) {
            return url;
        }
        String[] s = splitUrl(url);
        List<NameValuePair> parse;
        if (s[1] != null) {
            parse = URLEncodedUtils.parse(s[1], Charset.defaultCharset());
        } else {
            parse = new ArrayList<>();
        }
//        System.out.println(parse);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            parse.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        String p = URLEncodedUtils.format(parse, Charset.defaultCharset());
//        System.out.println(p);
        return s[0] + "?" + p;
    }
 
Example 6
Project: meituanwaimai-sdk   File: BaseServiceImpl.java   View Source Code Vote up 6 votes
private JSONObject getResponseJsonObject(String httpMethod, String url, Object params) throws IOException, MtWmErrorException {

        HttpUriRequest httpUriRequest = null;
        String fullUrl = getBaseApiUrl() + url;
        List<NameValuePair> sysNameValuePairs = getSysNameValuePairs(fullUrl, params);
        List<NameValuePair> nameValuePairs = getNameValuePairs(params);
        if (HTTP_METHOD_GET.equals(httpMethod)) {
            sysNameValuePairs.addAll(nameValuePairs);
            HttpGet httpGet = new HttpGet(fullUrl + "?" + URLEncodedUtils.format(sysNameValuePairs, UTF_8));
            setRequestConfig(httpGet);
            httpUriRequest = httpGet;
        } else if (HTTP_METHOD_POST.equals(httpMethod)) {
            HttpPost httpPost = new HttpPost(fullUrl + "?" + URLEncodedUtils.format(sysNameValuePairs, UTF_8));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, UTF_8));
            setRequestConfig(httpPost);
            httpUriRequest = httpPost;
        }

        CloseableHttpResponse response = this.httpClient.execute(httpUriRequest);
        String resultContent = new BasicResponseHandler().handleResponse(response);
        JSONObject jsonObject = JSON.parseObject(resultContent);
        MtWmError error = MtWmError.fromJson(jsonObject);
        if (error != null) {
            logging(url, httpMethod, false, httpUriRequest.getURI() + "\nBody:" + JSON.toJSONString(params), resultContent);
            throw new MtWmErrorException(error.getErrorCode(), error.getErrorMsg());
        }
        logging(url, httpMethod, true, httpUriRequest.getURI() + "\nBody:" + JSON.toJSONString(params), resultContent);
        return jsonObject;
    }
 
Example 7
Project: sinacloud-sdk-java   File: HttpUtils.java   View Source Code Vote up 6 votes
/**
 * Creates an encoded query string from all the parameters in the specified
 * request.
 *
 * @param request
 *            The request containing the parameters to encode.
 *
 * @return Null if no parameters were present, otherwise the encoded query
 *         string for the parameters present in the specified request.
 */
public static String encodeParameters(Request<?> request) {
    List<NameValuePair> nameValuePairs = null;
    if (request.getParameters().size() > 0) {
        nameValuePairs = new ArrayList<NameValuePair>(request.getParameters().size());
        for (Entry<String, String> entry : request.getParameters().entrySet()) {
            nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
    }

    String encodedParams = null;
    if (nameValuePairs != null) {
        encodedParams = URLEncodedUtils.format(nameValuePairs, DEFAULT_ENCODING);
    }

    return encodedParams;
}
 
Example 8
Project: anyline   File: HttpClientUtil.java   View Source Code Vote up 6 votes
public static Source delete(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();
		}
	}
	Source result = new Source();
	if (null != pairs) {
		String params = URLEncodedUtils.format(pairs,encode);
		if (url.contains("?")) {
			url += "&" + params;
		} else {
			url += "?" + params;
		}
	}
	HttpDelete method = new HttpDelete(url);
	setHeader(method, headers);
	result = exe(client, method, encode);
	return result;
}
 
Example 9
Project: dr-elephant   File: Application.java   View Source Code Vote up 6 votes
/**
 * 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 10
Project: oauth-java-sdk   File: AuthorizeUrlUtils.java   View Source Code Vote up 6 votes
/**
 * get authorize url
 *
 * @param responseType code or token
 * @param clientId
 * @param redirectUri
 * @param scope
 * @param state
 * @return
 */
public static String getAuthorizeUrl(
        ResponseType responseType, long clientId, String redirectUri, String scope, String state) {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(CLIENT_ID, String.valueOf(clientId)));
    params.add(new BasicNameValuePair(RESPONSE_TYPE, responseType.getType()));
    if (StringUtils.isNotEmpty(scope)) {
        params.add(new BasicNameValuePair(SCOPE, scope));
    }
    if (StringUtils.isNotEmpty(state)) {
        params.add(new BasicNameValuePair(STATE, state));
    }
    params.add(new BasicNameValuePair(REDIRECT_URI, redirectUri));
    String query = URLEncodedUtils.format(params, GlobalConstants.DEFAULT_CHARSET);
    return String.format("%s?%s", getAuthorizeUrl(), query);
}
 
Example 11
Project: tool.lars   File: RepositoryContext.java   View Source Code Vote up 6 votes
protected void doPostBadAttachmentWithContent(String assetId,
                                              String name,
                                              Attachment attachment,
                                              byte[] content,
                                              ContentType contentType,
                                              int expectedRC,
                                              String expectedMessage)
        throws ClientProtocolException, IOException, InvalidJsonAssetException {

    List<NameValuePair> qparams = new ArrayList<>();
    qparams.add(new BasicNameValuePair("name", name));
    String url = "/assets/" + assetId + "/attachments?"
                 + URLEncodedUtils.format(qparams, "UTF-8");

    String response = doPostMultipart(url,
                                      name,
                                      attachment.toJson(),
                                      content,
                                      contentType,
                                      expectedRC);

    if (expectedMessage != null) {
        String errorMessage = parseErrorObject(response);
        assertEquals("Unexpected message from server", expectedMessage, errorMessage);
    }
}
 
Example 12
Project: idilia-java-sdk   File: DisambiguateRequest.java   View Source Code Vote up 6 votes
/**
 * Encodes the request as a multipart message for sending to the server.
 * 
 * @return MultipartEntity suitable for transmission in an HTTP request.
 */
@Override
public HttpEntity getContent() {
  
  // Add a part with as a form
  List<NameValuePair> parms = new ArrayList<NameValuePair>();
  getHttpQueryParms(parms);
  String parmsText = URLEncodedUtils.format(parms, Consts.UTF_8);
  
  MultipartEntityBuilder builder =  MultipartEntityBuilder.create()
      .addTextBody("parms", parmsText, ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8));
  
  for (FormBodyPart part: attachments)
    builder.addPart(part.getName(), part.getBody());
   
   return builder.build();
}
 
Example 13
Project: java-bitbankcc   File: Bitbankcc.java   View Source Code Vote up 5 votes
private List<Header> getPrivateRequestHeader(String path, List<NameValuePair> query) throws BitbankException {
    long nonce = System.currentTimeMillis();
    String queryString = URLEncodedUtils.format(query, "utf-8");
    if(query.size() > 0) queryString = "?" + queryString;
    String message = String.valueOf(nonce) + path + queryString;
    return makePrivateRequestHeader(nonce, createSign(message));
}
 
Example 14
Project: Equella   File: HttpServiceImpl.java   View Source Code Vote up 5 votes
@Nullable
private String queryStringNv(@Nullable List<NameValuePair> params)
{
	if( params == null )
	{
		return null;
	}
	return URLEncodedUtils.format(params, Constants.UTF8);
}
 
Example 15
Project: Equella   File: AbstractRestApiTest.java   View Source Code Vote up 5 votes
/**
 * Turns a list of NameValuePair into a query string. e.g
 * param1=val1&param2=val2
 * 
 * @param params
 * @return
 */
public String queryString(List<NameValuePair> params)
{
	if( params == null )
	{
		return null;
	}
	return URLEncodedUtils.format(params, "UTF-8");
}
 
Example 16
Project: Equella   File: AbstractItemApiTest.java   View Source Code Vote up 5 votes
protected JsonNode basicSearch(String query, String token, boolean showAll) throws Exception
{
	List<NameValuePair> params = Lists.newArrayList();
	params.add(new BasicNameValuePair("q", query));
	String paramString = URLEncodedUtils.format(params, "UTF-8");
	HttpGet get = new HttpGet(context.getBaseUrl() + "api/search?showall=" + showAll + "&" + paramString);
	HttpResponse response = execute(get, false, token);
	return mapper.readTree(response.getEntity().getContent());
}
 
Example 17
Project: weixinpay   File: HttpUtil.java   View Source Code Vote up 5 votes
public static String getUrl(String url, List<NameValuePair> params) {
    String uri = url;
    if (params != null) uri += URLEncodedUtils.format(params, "UTF-8");
    //System.out.println(uri.toString());
    log.info(uri.toString());

    HttpGet httpget = new HttpGet(uri);
    HttpClient httpclient = new DefaultHttpClient();

    httpclient.getParams().setParameter(HttpProtocolParams.HTTP_CONTENT_CHARSET, "UTF-8");
    //请求超时 ,连接超时
    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
    //读取超时
    httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);

    String rs = "";

    try {
        HttpResponse response = httpclient.execute(httpget);//  httpClient.executeMethod(postMethod);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            rs = EntityUtils.toString(response.getEntity(), "UTF-8");


            log.info("rs: " + rs);

            return rs;
        } else {
            System.out.println("rs: not HttpStatus.SC_OK");
        }
    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        httpclient.getConnectionManager().shutdown();
    }
    return rs;
}
 
Example 18
Project: desafio-pagarme   File: Client.java   View Source Code Vote up 5 votes
private HttpRequest addTokenInURI(HttpRequest request) throws IOException, URISyntaxException{
	ClientHttpRequest clientRequest = (ClientHttpRequest) request;
	List<NameValuePair> params = new ArrayList<>() ; 
	params.add(new BasicNameValuePair("api_key",  this.apiKey));
	String url 	  = URLEncodedUtils.format(params, "UTF-8");
	URI src    	  = new URI(request.getURI().toString().concat("?").concat(url));
	clientRequest = new HttpComponentsClientHttpRequestFactory().createRequest(src, request.getMethod());
	return clientRequest;
}
 
Example 19
Project: E621Mobile   File: E621.java   View Source Code Vote up 5 votes
public E621Image post__show(Integer id) throws IOException
{
	String base = String.format("%s/post/show.json?",DOMAIN_NAME);
	
	List<NameValuePair> params = new LinkedList<NameValuePair>();
	
	params.add(new BasicNameValuePair("id", String.valueOf(id)));
	
	base += URLEncodedUtils.format(params, "utf-8");
	
	HttpResponse response = tryHttpGet(base,5);
    StatusLine statusLine = response.getStatusLine();
    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        out.close();
        String responseString = out.toString();
        
        try {
			return E621Image.fromJSON(new JSONObject(responseString));
		} catch (JSONException e) {
			return null;
		}
        
    } else{
        //Closes the connection.
        response.getEntity().getContent().close();
        throw new IOException(statusLine.getReasonPhrase());
    }
}
 
Example 20
Project: Newton_for_Android_AS   File: HTTPUtil.java   View Source Code Vote up 5 votes
/**
 * 组装URL
 * @param url
 * @param params
 * @return
 */
public static String getUrl(String url, List<BasicNameValuePair> params) {
	String urlParams = "";
	if (params != null && !params.isEmpty()) {
		urlParams = URLEncodedUtils.format(params, "UTF-8");
	}
	
	if (!TextUtils.isEmpty(urlParams)) {
		url += "?" + urlParams;
	}
	
	return url;
}
 
Example 21
Project: MBLive   File: WebKit.java   View Source Code Vote up 5 votes
public static String buildQueryStr(HttpServletRequest request) {
    List result = new ArrayList();
    Enumeration parameterNames = request.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String key = String.valueOf(parameterNames.nextElement());
        String[] values = request.getParameterValues(key);
        for (String value : values) {
            result.add(new BasicNameValuePair(key, value));
        }
    }
    return URLEncodedUtils.format(result, Charset.forName("UTF-8"));
}
 
Example 22
Project: metrika_android   File: RequestHelper.java   View Source Code Vote up 5 votes
private String addParamsToUrl(List<NameValuePair> params, String url){
    if(params==null || params.size()==0) return url;
    if(!url.endsWith("?"))
        url += "?";
    List<NameValuePair> nameValuePairs = params;
    if(nameValuePairs!=null){
        String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8");
        url += paramString;
    }
    return url;
}
 
Example 23
Project: substitution-schedule-parser   File: ESchoolParser.java   View Source Code Vote up 5 votes
@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 24
Project: purecloud-iot   File: Request.java   View Source Code Vote up 5 votes
public Request bodyForm(final Iterable <? extends NameValuePair> formParams, final Charset charset) {
    final List<NameValuePair> paramList = new ArrayList<NameValuePair>();
    for (NameValuePair param : formParams) {
        paramList.add(param);
    }
    final ContentType contentType = ContentType.create(URLEncodedUtils.CONTENT_TYPE, charset);
    final String s = URLEncodedUtils.format(paramList, charset != null ? charset.name() : null);
    return bodyString(s, contentType);
}
 
Example 25
Project: certificate-transparency-java   File: HttpInvoker.java   View Source Code Vote up 5 votes
/**
 * Makes an HTTP GET method call to the given URL with the provides parameters.
 *
 * @param url URL for GET method.
 * @param params query parameters.
 * @return Server's response body.
 */
public String makeGetRequest(String url, List<NameValuePair> params) {
  try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
    String paramsStr = "";
    if (params != null) {
      paramsStr = "?" + URLEncodedUtils.format(params, "UTF-8");
    }
    HttpGet get = new HttpGet(url + paramsStr);
    get.addHeader("Content-Type", "application/json; charset=utf-8");

    return httpClient.execute(get, new BasicResponseHandler());
  } catch (IOException e) {
    throw new LogCommunicationException("Error making GET request to " + url, e);
  }
}
 
Example 26
Project: foursquared   File: AbstractHttpApi.java   View Source Code Vote up 5 votes
public HttpGet createHttpGet(String url, NameValuePair... nameValuePairs) {
    if (DEBUG) LOG.log(Level.FINE, "creating HttpGet for: " + url);
    String query = URLEncodedUtils.format(stripNulls(nameValuePairs), HTTP.UTF_8);
    HttpGet httpGet = new HttpGet(url + "?" + query);
    httpGet.addHeader(CLIENT_VERSION_HEADER, mClientVersion);
    if (DEBUG) LOG.log(Level.FINE, "Created: " + httpGet.getURI());
    return httpGet;
}
 
Example 27
Project: foursquared.eclair   File: AbstractHttpApi.java   View Source Code Vote up 5 votes
public HttpGet createHttpGet(String url, NameValuePair... nameValuePairs) {
    if (DEBUG) LOG.log(Level.FINE, "creating HttpGet for: " + url);
    String query = URLEncodedUtils.format(stripNulls(nameValuePairs), HTTP.UTF_8);
    HttpGet httpGet = new HttpGet(url + "?" + query);
    httpGet.addHeader(CLIENT_VERSION_HEADER, mClientVersion);
    if (DEBUG) LOG.log(Level.FINE, "Created: " + httpGet.getURI());
    return httpGet;
}
 
Example 28
Project: eshow-android   File: AbRequestParams.java   View Source Code Vote up 5 votes
/**
 * 获取参数字符串.
 * 
 * @return the param string
 */
public String getParamString() {
	List<BasicNameValuePair> paramsList = new LinkedList<BasicNameValuePair>();
	for (ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {
		paramsList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
	}
	return URLEncodedUtils.format(paramsList, HTTP.UTF_8);
}
 
Example 29
Project: egov-mobile   File: ComplaintDetailActivity.java   View Source Code Vote up 5 votes
private String generateDownloadImageURL(String downImgURL,
		List<NameValuePair> params) {
	try {
		if (!downImgURL.endsWith("?")) {
			downImgURL += "?";
		}
		String paramString = URLEncodedUtils.format(params, "utf-8");
		downImgURL += paramString;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return downImgURL;
}
 
Example 30
Project: FMTech   File: HtmlFormContent.java   View Source Code Vote up 5 votes
private String buildUrlEncodedString()
{
  if (this.mEntries == null) {
    return null;
  }
  ArrayList localArrayList = new ArrayList(this.mEntries.length());
  int i = 0;
  int j = this.mEntries.length();
  for (;;)
  {
    if (i >= j) {
      break label101;
    }
    try
    {
      JSONObject localJSONObject = this.mEntries.optJSONObject(i);
      if (localJSONObject != null) {
        localArrayList.add(new BasicNameValuePair(localJSONObject.getString("name"), localJSONObject.getString("value")));
      }
      i++;
    }
    catch (JSONException localJSONException)
    {
      for (;;)
      {
        Log.e("HtmlFormContent", "Failed to parse JSON object", localJSONException);
      }
    }
  }
  label101:
  return URLEncodedUtils.format(localArrayList, "UTF-8");
}
 
Example 31
Project: java-aci-api-ng   File: AciHttpClientImplTest.java   View Source Code Vote up 5 votes
@Test
@SuppressWarnings("unchecked")
public void testCreateEncryptedParameters() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, EncryptionCodecException {
    // Create our client...
    final AciHttpClientImpl aciHttpClient = new AciHttpClientImpl();

    // Get our method...
    final Method method = ReflectionTestUtils.getAccessibleMethod(AciHttpClientImpl.class, "createEncryptedParameters", AciServerDetails.class, Set.class);

    // Add an encryption codec to the server details... 
    serverDetails.setEncryptionCodec(new TestEncryptionCodec());

    // Here's the parameter set...
    final Set<AciParameter> parameters = new LinkedHashSet<>();
    parameters.add(new AciParameter(AciConstants.PARAM_ACTION, "query"));
    parameters.add(new AciParameter("Text", "This is some text..."));

    // Invoke the method with the parameters...
    final Set<AciParameter> encrypted = (Set<AciParameter>) method.invoke(aciHttpClient, serverDetails, parameters);

    // Correctly encode the query string before encrypting it...
    final String queryString = URLEncodedUtils.format(Arrays.asList(new BasicNameValuePair(AciConstants.PARAM_ACTION, "query"), new BasicNameValuePair("Text", "This is some text...")), "UTF-8");
    final String encryptedQueryString = EncryptionCodecUtils.getInstance().encrypt(serverDetails.getEncryptionCodec(), queryString, serverDetails.getCharsetName());

    // Check the encrypted parameters...
    assertThat("Incorrect query string", encrypted, hasItems(
            new AciParameter(AciConstants.PARAM_ACTION, AciConstants.ACTION_ENCRYPTED),
            new AciParameter(AciConstants.PARAM_DATA, encryptedQueryString)
    ));
}
 
Example 32
Project: android-wear-voice-message   File: MobileActivity.java   View Source Code Vote up 5 votes
private MessageApi.MessageListener messageListenerFactory(){
    return new MessageApi.MessageListener() {
        @Override
        public void onMessageReceived(MessageEvent messageEvent) {
            if (messageEvent.getPath().equals(COMMAND_PATH)) {

                RobotCommand robotCommand = new RobotCommand(new String(messageEvent.getData()));
                command = robotCommand.getCommand();

                if(!command.isEmpty()) {
                    StringBuilder requestUrl = new StringBuilder(BASE_URL);
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("name",command));
                    params.add(new BasicNameValuePair("queue","1"));
                    String queryString = URLEncodedUtils.format(params, "utf-8");
                    requestUrl.append("?");
                    requestUrl.append(queryString);
                    HttpClient httpclient = new DefaultHttpClient();
                    try {
                        httpclient.execute(new HttpGet(requestUrl.toString()));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else{
                    //TODO: NO DETECTED COMMAND
                }
            }
        }
    };
}
 
Example 33
Project: libtincent   File: TXSignUtil.java   View Source Code Vote up 5 votes
/**
 * 生成签名字符串
 * 
 * @param url
 *            网络地址
 * @param method
 *            请求方法
 * @param params
 *            请求参数
 * @param appsecret
 *            签名密钥
 * @param dbg
 *            是否开启调试:调式模式可打印签名日志
 * @return
 */
public String makeSign(String url, String method, RequestParams params, String appsecret, boolean dbg) {
	StringBuilder sb = new StringBuilder();
	sb.append(method).append("&");
	sb.append(Uri.encode(url)).append("&");
	// 排序
	List<BasicNameValuePair> basicNameValuePairs = params.getParamsList();
	Collections.sort(basicNameValuePairs, paramsCompre);
	String paramStr = URLEncodedUtils.format(basicNameValuePairs, "UTF-8");
	sb.append(Uri.encode(paramStr));

	String digit = TXSHAUtil.getSHA1(sb.toString());

	byte[] encrypt = TXXXTEA.encrypt(digit.getBytes(), appsecret.getBytes());

	String base64 = Base64.encodeToString(encrypt, Base64.DEFAULT);

	String sign = Uri.encode(base64);

	if (dbg) {
		TXDebug.o(new Exception(), "url : " + sb.toString());
		TXDebug.o(new Exception(), "digit : " + digit);
		TXDebug.o(new Exception(), "base64 : " + base64);
		TXDebug.o(new Exception(), "sign : " + sign);
	}
	
	params.put("sign", sign);

	return sign;
}
 
Example 34
Project: FHWS-MobileApplikationen   File: MainActivity.java   View Source Code Vote up 5 votes
@Override
protected Integer doInBackground(String... url) {
	
	AndroidHttpClient httpClient = AndroidHttpClient.newInstance("test");
	List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	nameValuePairs.add(new BasicNameValuePair("size", Integer.toString(100)));
	nameValuePairs.add(new BasicNameValuePair("pause", Integer.toString(10)));
	
	HttpGet get = new HttpGet("http://" + HOST + ":8080/fhws/progress?" + URLEncodedUtils.format(nameValuePairs, "UTF-8"));
	
	int size = 0;
	
	try
	{
		HttpResponse response = httpClient.execute(get);
		size = Integer.parseInt(response.getFirstHeader(HTTP.CONTENT_LEN).getValue());
		
		InputStream is = response.getEntity().getContent();
		
		for( int i=0; i<size; i++ )
		{
			is.read();
			int progress = (int)((i/(float)size)*100);
			publishProgress(progress);
		}
		
	}
	catch( Exception e )
	{
		e.printStackTrace();
	}
	
	return size;
}
 
Example 35
Project: hops   File: WebAppUtils.java   View Source Code Vote up 5 votes
private static String getURLEncodedQueryString(HttpServletRequest request) {
  String queryString = request.getQueryString();
  if (queryString != null && !queryString.isEmpty()) {
    String reqEncoding = request.getCharacterEncoding();
    if (reqEncoding == null || reqEncoding.isEmpty()) {
      reqEncoding = "ISO-8859-1";
    }
    Charset encoding = Charset.forName(reqEncoding);
    List<NameValuePair> params = URLEncodedUtils.parse(queryString, encoding);
    return URLEncodedUtils.format(params, encoding);
  }
  return null;
}
 
Example 36
Project: riscoss-data-collector   File: RiscossRESTClient.java   View Source Code Vote up 5 votes
private String send( SendOption<?> opt ) {
	
	try {
		
		method.setConfig(requestConfig);
		
		if( params.size() != 0 ) {
			StringBuilder requestUrl = new StringBuilder( method.getURI().toString() );
			String querystring = URLEncodedUtils.format( params, "utf-8");
			requestUrl.append("?");
			requestUrl.append(querystring);
			method.setURI( new URI( requestUrl.toString() ) );
		}
		
		System.out.print( mklength( method.getMethod(), 6 ) + " " + method.getURI() );
		
		if( opt != null ) {
			opt.applyTo( method );
		}
		
		HttpResponse response = client.execute( method );
		if (response.getStatusLine().getStatusCode() == 200) {
			HttpEntity entity = response.getEntity();
			String ret = EntityUtils.toString(entity);
			System.out.println( "     RETURNED: " + ret );
			return ret;
		} else {
			System.out.println( "     RETURNED:");
			// something has gone wrong...
			return null; //response.getStatusLine().toString();
		}
	}
	catch( Exception ex ) {
		throw new RuntimeException( ex );
	}
}
 
Example 37
Project: Mobike   File: RequestParams.java   View Source Code Vote up 4 votes
protected String getParamString() {
    return URLEncodedUtils.format(getParamsList(), contentEncoding);
}
 
Example 38
Project: sealtalk-android-master   File: RequestParams.java   View Source Code Vote up 4 votes
public String getParamString() {
    return URLEncodedUtils.format(getParamsList(), HTTP.UTF_8);
}
 
Example 39
Project: careconnect-reference-implementation   File: GatewayCamelProcessor.java   View Source Code Vote up 4 votes
@Override
public void process(Exchange exchange) throws Exception {



    if (exchange.getIn().getBody() instanceof HttpServletRequest) {
        // This is a result of a passthrough operation in the resource provider.

        HttpServletRequest httpRequest = (HttpServletRequest) exchange.getIn().getBody();

        exchange.getIn().removeHeaders("*" );

        exchange.getIn().setBody(httpRequest.getInputStream());

        exchange.getIn().setHeader(Exchange.HTTP_METHOD, httpRequest.getMethod());

        if (httpRequest.getQueryString() != null) {

            //log.info("QueryString = "+httpRequest.getQueryString());
            List<NameValuePair> params = URLEncodedUtils.parse(new URI("http://dummy?" + httpRequest.getQueryString()), "UTF-8");

            ListIterator paramlist = params.listIterator();
            while (paramlist.hasNext()) {
                // Remove format. This causes errors in the server (internally we work in JSON only)
                // KGM 3/1/2018
                NameValuePair param = (NameValuePair) paramlist.next();
                // log.info("QS Name ="+param.getName()+" Value="+param.getValue());
                if (param.getName().equals("_format")) paramlist.remove();

            }
            String queryString = URLEncodedUtils.format(params, "UTF-8");
            //log.info("New QS="+queryString);

            exchange.getIn().setHeader(Exchange.HTTP_QUERY, queryString);
        } else {
            exchange.getIn().setHeader(Exchange.HTTP_QUERY, null);
        }


        exchange.getIn().setHeader(Exchange.HTTP_PATH, httpRequest.getPathInfo());

        if (httpRequest.getRemoteAddr() !=null && !httpRequest.getRemoteAddr().isEmpty()) {
            exchange.getIn().setHeader("X-Forwarded-For", httpRequest.getRemoteAddr());
        }
        if (httpRequest.getRemoteHost() !=null && !httpRequest.getRemoteHost().isEmpty()) {
            exchange.getIn().setHeader("X-Forwarded-Host", httpRequest.getRemoteHost());
        }
    }

    exchange.getIn().setHeader(Exchange.ACCEPT_CONTENT_TYPE, "application/json");

    if (exchange.getIn().getHeader("X-Request-ID") == null || exchange.getIn().getHeader("X-Request-ID").toString().isEmpty()) {
        exchange.getIn().setHeader("X-Request-ID",exchange.getExchangeId());
    }

}
 
Example 40
Project: letv   File: RequestParams.java   View Source Code Vote up 4 votes
protected String getParamString() {
    return URLEncodedUtils.format(getParamsList(), ENCODING);
}
 
Example 41
Project: rongyunDemo   File: RequestParams.java   View Source Code Vote up 4 votes
public String getParamString() {
    return URLEncodedUtils.format(getParamsList(), HTTP.UTF_8);
}
 
Example 42
Project: desafio-pagarme   File: Client.java   View Source Code Vote up 4 votes
@Override
public <T> T get(List<NameValuePair> vars, Class<T> class1) throws JsonParseException, JsonMappingException, IOException, HttpServerErrorException {
	String url = URLEncodedUtils.format(vars, "UTF-8");
	return this.restTemplate.getForObject(getURI(class1).concat("?").concat(url), class1);
}
 
Example 43
Project: android-project-gallery   File: RequestParams.java   View Source Code Vote up 4 votes
protected String getParamString() {
    return URLEncodedUtils.format(getParamsList(), contentEncoding);
}
 
Example 44
Project: boohee_v5.6   File: RequestParams.java   View Source Code Vote up 4 votes
protected String getParamString() {
    return URLEncodedUtils.format(getParamsList(), this.contentEncoding);
}
 
Example 45
Project: sealtalk-android   File: RequestParams.java   View Source Code Vote up 4 votes
public String getParamString() {
    return URLEncodedUtils.format(getParamsList(), HTTP.UTF_8);
}
 
Example 46
Project: ROKO.Stickers-Android   File: RequestParams.java   View Source Code Vote up 4 votes
protected String getParamString() {
    return URLEncodedUtils.format(getParamsList(), ENCODING);
}
 
Example 47
Project: RongChat   File: RequestParams.java   View Source Code Vote up 4 votes
public String getParamString() {
    return URLEncodedUtils.format(getParamsList(), HTTP.UTF_8);
}
 
Example 48
Project: diadocsdk-java   File: DiadocApi.java   View Source Code Vote up 4 votes
private URI BuildRequestURI(URI baseUri, String path, List<NameValuePair> parameters) throws URISyntaxException {
    String query = parameters != null ? URLEncodedUtils.format(parameters, "UTF-8") : null;
    String uriPath = Tools.concatUriPath(baseUri.getPath(), path);
    return URIUtils.createURI(baseUri.getScheme(), baseUri.getHost(), baseUri.getPort(), uriPath, query, null);
}
 
Example 49
Project: MiBandDecompiled   File: RequestParams.java   View Source Code Vote up 4 votes
protected String getParamString()
{
    return URLEncodedUtils.format(getParamsList(), contentEncoding);
}
 
Example 50
Project: EveryXDay   File: RequestParams.java   View Source Code Vote up 4 votes
public String getParamString() {
	return URLEncodedUtils.format(getParamsList(), contentEncoding);
}
 
Example 51
Project: Android-Basics-Codes   File: AjaxParams.java   View Source Code Vote up 4 votes
public String getParamString() {
    return URLEncodedUtils.format(getParamsList(), ENCODING);
}
 
Example 52
Project: AndroidNetworkRequest   File: JsonRequest.java   View Source Code Vote up 4 votes
@Override
protected String getPostParams() {
    return URLEncodedUtils.format(mParamsList, HTTP.UTF_8);
}
 
Example 53
Project: Android-NRInject   File: mainListView.java   View Source Code Vote up 4 votes
@Override
protected Boolean doInBackground(String... urls) {
    try {

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("id", urls[2]));
        //------------------>>
        String finalURL = String.format("http://%s/injector/inject",urls[0]);
        String finalPass = urls[1];
        //------------------>>
        HttpGet httpget = new HttpGet(finalURL + "?" + URLEncodedUtils.format(params, "utf-8"));

        httpget.setHeader("AUTH", finalPass);

        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        // The default value is zero, that means the timeout is not used.
        int timeoutConnection = 3000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

        HttpResponse response = httpClient.execute(httpget);

        int status = response.getStatusLine().getStatusCode();

        if (status == 200) {

            /*
            *need to alert on the main thread
            * */
            return true;
        }

        //------------------>>

    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}
 
Example 54
Project: youtrack-worklog-viewer   File: UrlBuilder.java   View Source Code Vote up 4 votes
@Override
public String getIssueDetailsUrl(List<NameValuePair> fetchIssuesParameters) {
    String template = buildYoutrackApiUrl("/rest/issue?%s");
    String issuesQuery = URLEncodedUtils.format(fetchIssuesParameters, Charset.forName("utf-8"));
    return String.format(template, issuesQuery);
}
 
Example 55
Project: Please   File: Form.java   View Source Code Vote up 4 votes
/**
 * Builds the HttpEntity from this form.
 */
protected HttpEntity getEntity(String charset) {
    String body = URLEncodedUtils.format(fields, charset);
    return new StringEntity(body, ContentType.APPLICATION_FORM_URLENCODED);
}
 
Example 56
Project: lams   File: UrlEncodedFormEntity.java   View Source Code Vote up 3 votes
/**
 * Constructs a new {@link UrlEncodedFormEntity} with the list
 * of parameters in the specified encoding.
 *
 * @param parameters list of name/value pairs
 * @param charset encoding the name/value pairs be encoded with
 * @throws UnsupportedEncodingException if the encoding isn't supported
 */
public UrlEncodedFormEntity (
    final List <? extends NameValuePair> parameters,
    final String charset) throws UnsupportedEncodingException {
    super(URLEncodedUtils.format(parameters,
            charset != null ? charset : HTTP.DEF_CONTENT_CHARSET.name()),
            ContentType.create(URLEncodedUtils.CONTENT_TYPE, charset));
}
 
Example 57
Project: purecloud-iot   File: UrlEncodedFormEntity.java   View Source Code Vote up 3 votes
/**
 * Constructs a new {@link UrlEncodedFormEntity} with the list
 * of parameters in the specified encoding.
 *
 * @param parameters iterable collection of name/value pairs
 * @param charset encoding the name/value pairs be encoded with
 *
 * @since 4.2
 */
public UrlEncodedFormEntity (
    final Iterable <? extends NameValuePair> parameters,
    final Charset charset) {
    super(URLEncodedUtils.format(parameters,
            charset != null ? charset : HTTP.DEF_CONTENT_CHARSET),
            ContentType.create(URLEncodedUtils.CONTENT_TYPE, charset));
}
 
Example 58
Project: purecloud-iot   File: UrlEncodedFormEntity.java   View Source Code Vote up 3 votes
/**
 * Constructs a new {@link UrlEncodedFormEntity} with the list
 * of parameters in the specified encoding.
 *
 * @param parameters list of name/value pairs
 * @param charset encoding the name/value pairs be encoded with
 * @throws UnsupportedEncodingException if the encoding isn't supported
 */
public UrlEncodedFormEntity (
    final List <? extends NameValuePair> parameters,
    final String charset) throws UnsupportedEncodingException {
    super(URLEncodedUtils.format(parameters,
            charset != null ? charset : HTTP.DEF_CONTENT_CHARSET.name()),
            ContentType.create(URLEncodedUtils.CONTENT_TYPE, charset));
}
 
Example 59
Project: sling-org-apache-sling-testing-clients   File: URLParameterBuilder.java   View Source Code Vote up 2 votes
/**
 * Build the URL parameters
 *
 * @return The URL parameters string without the leading question mark.
 */
public String getURLParameters() {
    return URLEncodedUtils.format(params, encoding);
}
 
Example 60
Project: ss-android   File: NetUtils.java   View Source Code Vote up 2 votes
/**
 * 这里使用了HttpClinet的API。只是为了方便
 * @param params
 * @return
 */
public static String formatParams(List<BasicNameValuePair> params){
    return URLEncodedUtils.format(params, CHARSET_NAME);
}