Java Code Examples for org.apache.http.NameValuePair

The following are top voted examples for showing how to use org.apache.http.NameValuePair. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: smn-sdk-java   File: ListTopicsRequest.java   View source code 6 votes vote down vote up
/**
 * obtain the get request param
 *
 * @return the param string
 */
private String getRequestParamString() {
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

    nameValuePairs.add(new BasicNameValuePair(SmnConstants.OFFSET, String.valueOf(offset)));
    nameValuePairs.add(new BasicNameValuePair(SmnConstants.LIMIT, String.valueOf(limit)));

    String param = "";
    if (!nameValuePairs.isEmpty()) {
        try {
            param = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs, Charset.forName("UTF-8")));
        } catch (IOException e) {
            throw new RuntimeException("get request param error");
        }
    }
    return param;
}
 
Example 2
Project: publicProject   File: HttpClientStack.java   View source code 6 votes vote down vote up
@SuppressWarnings("unused")
private static List<NameValuePair> getPostParameterPairs(Map<String, String> postParams) {
    List<NameValuePair> result = new ArrayList<NameValuePair>(postParams.size());
    for (String key : postParams.keySet()) {
        result.add(new BasicNameValuePair(key, postParams.get(key)));
    }
    return result;
}
 
Example 3
Project: lams   File: URLEncodedUtils.java   View source code 6 votes vote down vote up
/**
 * Returns a String that is suitable for use as an <code>application/x-www-form-urlencoded</code>
 * list of parameters in an HTTP PUT or HTTP POST.
 *
 * @param parameters  The parameters to include.
 * @param encoding The encoding to use.
 */
public static String format (
        final List <? extends NameValuePair> parameters,
        final String encoding) {
    final StringBuilder result = new StringBuilder();
    for (final NameValuePair parameter : parameters) {
        final String encodedName = encodeFormFields(parameter.getName(), encoding);
        final String encodedValue = encodeFormFields(parameter.getValue(), encoding);
        if (result.length() > 0) {
            result.append(PARAMETER_SEPARATOR);
        }
        result.append(encodedName);
        if (encodedValue != null) {
            result.append(NAME_VALUE_SEPARATOR);
            result.append(encodedValue);
        }
    }
    return result.toString();
}
 
Example 4
Project: nextcloud-java-api   File: ConnectorCommon.java   View source code 6 votes vote down vote up
private URI buildUrl(String subPath, List<NameValuePair> queryParams)
{
    URIBuilder uB= new URIBuilder()
    .setScheme(serverConfig.isUseHTTPS() ? "https" : "http")
    .setHost(serverConfig.getServerName())
    .setUserInfo(serverConfig.getUserName(), serverConfig.getPassword())
    .setPath(subPath);
    if (queryParams != null)
    {
        uB.addParameters(queryParams);
    }
    try {
        return uB.build();
    } catch (URISyntaxException e) {
        throw new NextcloudApiException(e);
    }
}
 
Example 5
Project: GitHub   File: HttpClientStack.java   View source code 5 votes vote down vote up
@SuppressWarnings("unused")
private static List<NameValuePair> getPostParameterPairs(Map<String, String> postParams) {
    List<NameValuePair> result = new ArrayList<NameValuePair>(postParams.size());
    for (String key : postParams.keySet()) {
        result.add(new BasicNameValuePair(key, postParams.get(key)));
    }
    return result;
}
 
Example 6
Project: Huochexing12306   File: A6OrderAty.java   View source code 5 votes vote down vote up
private boolean cancelOrder(BookingInfo bInfo) {
	String url = "https://kyfw.12306.cn/otn/queryOrder/cancelNoCompleteMyOrder";
	List<NameValuePair> lstParams = new ArrayList<NameValuePair>();
	lstParams.add(new BasicNameValuePair("sequence_no", mLstODBInfos.get(0)
			.getSequence_no()));
	lstParams.add(new BasicNameValuePair("cancel_flag", "cancel_order"));
	lstParams.add(new BasicNameValuePair("_json_att", ""));
	try {
		A6Info a6Json = A6Util
				.post(bInfo,
						A6Util.makeRefererColl("https://kyfw.12306.cn/otn/queryOrder/initNoComplete"),
						url, lstParams);
		JSONObject jsonObj = new JSONObject(a6Json.getData());
		if (jsonObj.getString("existError").equals("N")) {
			return true;
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return false;
}
 
Example 7
Project: k8s-proxy   File: GoogleTokenRetriever.java   View source code 5 votes vote down vote up
public GoogleIdAndRefreshToken postForRefreshAndAccessToken(String code, String redirectUri) throws IOException
{
    HttpPost callbackRequest = new HttpPost(tokenUrl);

    List<NameValuePair> parameters = new ArrayList<>();
    parameters.addAll(getAuthenticationParameters());
    parameters.addAll(Arrays.asList(new BasicNameValuePair("grant_type", "authorization_code"),
                                    new BasicNameValuePair("code", code),
                                    new BasicNameValuePair("redirect_uri", redirectUri)));
    callbackRequest.setEntity(new UrlEncodedFormEntity(parameters, StandardCharsets.UTF_8));

    try (CloseableHttpResponse callbackResponse = httpClient.execute(callbackRequest)) {
        GoogleIdAndRefreshToken googleToken = objectMapper.readValue(IOUtils.toString(callbackResponse.getEntity()
                                                                                                      .getContent(),
                                                                                      StandardCharsets.UTF_8),
                                                                     GoogleIdAndRefreshToken.class);
        logger.info("New id token retrieved.");
        return googleToken;
    }
}
 
Example 8
Project: SPLGroundControl   File: RockBlockHttpHandler.java   View source code 5 votes vote down vote up
public IridiumMessage(List<NameValuePair> params) {
    for (NameValuePair param : params) {
        switch (param.getName()) {
            case PARAM_IMEI:
                imei = param.getValue();
                break;
            case PARAM_MOMSN:
                momsn = param.getValue();
                break;
            case PARAM_TRANSMIT_TIME:
                transmitTime = param.getValue();
                break;
            case PARAM_IRIDIUM_LATITUDE:
                iridiumLatitude = param.getValue();
                break;
            case PARAM_IRIDIUM_LONGITUDE:
                iridiumLongitude = param.getValue();
                break;
            case PARAM_IRIDIUM_CEP:
                iridiumCep = param.getValue();
                break;
            case PARAM_DATA:
                data = param.getValue();
                break;
        }
    }
}
 
Example 9
Project: delivery-sdk-java   File: DeliveryParameterBuilderTest.java   View source code 5 votes vote down vote up
@Test
public void testGreaterThan() {
    List<NameValuePair> params = DeliveryParameterBuilder.params().filterGreaterThan("foo", "bar").build();
    Assert.assertEquals(1, params.size());
    Assert.assertEquals("foo[gt]", params.get(0).getName());
    Assert.assertEquals("bar", params.get(0).getValue());
}
 
Example 10
Project: smn-sdk-java   File: ListMessageTemplatesRequest.java   View source code 5 votes vote down vote up
/**
 * obtain the get request param
 *
 * @return the param string
 */
private String getRequestParamString() {
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    if (!StringUtils.isBlank(protocol)) {
        nameValuePairs.add(new BasicNameValuePair(SmnConstants.SMN_PROTOCOL, protocol));
    }

    if (!StringUtils.isBlank(messageTemplateName)) {
        nameValuePairs.add(new BasicNameValuePair(SmnConstants.SMN_MESSAGE_TEMPLATE_NAME, messageTemplateName));
    }

    nameValuePairs.add(new BasicNameValuePair(SmnConstants.OFFSET, String.valueOf(offset)));
    nameValuePairs.add(new BasicNameValuePair(SmnConstants.LIMIT, String.valueOf(limit)));

    String param = "";
    if (!nameValuePairs.isEmpty()) {
        try {
            param = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs, Charset.forName("UTF-8")));
        } catch (IOException e) {
            throw new RuntimeException("get request param error");
        }
    }
    return param;
}
 
Example 11
Project: xvms   File: SiteActions.java   View source code 5 votes vote down vote up
/**
 * 获取当前登陆账号后台权限所有栏目列表
 *
 */
public String getWebPosition() throws Exception{
	List <NameValuePair> nvps = new ArrayList <NameValuePair>();
       //网页post参数 http://www.xxx.com/appqy_api/api.php?api_key=AaPpQqYyCcOoMmLl&opt=getCategory
       nvps.add(new BasicNameValuePair("api_key", WEB_KEY));
       nvps.add(new BasicNameValuePair("opt", "getPosition"));
       return ht.doPost(WEB_PATH,nvps,CookieStatus);
}
 
Example 12
Project: ts-benchmark   File: InfluxDB.java   View source code 5 votes vote down vote up
@Override
public Status selectMinuteAvgByDeviceAndSensor(TsPoint point, Date startTime, Date endTime) {
	HttpClient hc = getHttpClient();
	HttpPost post = new HttpPost(QUERY_URL);
	HttpResponse response = null;
	long costTime = 0L;
	try {
		List<NameValuePair> nameValues = new ArrayList<NameValuePair>();
		String selectSql = "SELECT MEAN(value) FROM sensor where device_code='" + point.getDeviceCode()
				+ "' and sensor_code='" + point.getSensorCode() + "' and time>=" + TimeUnit.MILLISECONDS.toNanos(startTime.getTime())
				+ " and time<=" + TimeUnit.MILLISECONDS.toNanos(endTime.getTime()) + " group by time(1m)";
		NameValuePair nameValue = new BasicNameValuePair("q", selectSql);
		nameValues.add(nameValue);
		HttpEntity entity = new UrlEncodedFormEntity(nameValues, "utf-8");
		post.setEntity(entity);
		long startTime1 = System.nanoTime();
		response = hc.execute(post);
		long endTime1 = System.nanoTime();
		costTime = endTime1 - startTime1;
	} catch (Exception e) {
		e.printStackTrace();
		return Status.FAILED(-1);
	}finally{
		closeResponse(response);
		closeHttpClient(hc);
	}
	return Status.OK(costTime);
}
 
Example 13
Project: momo-2   File: WebServer.java   View source code 5 votes vote down vote up
/**
 * Perform an Oauth2 callback to the Discord servers with the token given by the user's approval
 * @param token Token from user
 * @param res Passed on response
 * @throws ClientProtocolException Error in HTTP protocol
 * @throws IOException Encoding exception or error in protocol
 * @throws NoAPIKeyException No API keys set
 */
static void oauth(String token, Response res) throws ClientProtocolException, IOException, NoAPIKeyException {
	
	CloseableHttpClient httpclient = HttpClients.createDefault();

	HttpPost post = new HttpPost("https://discordapp.com/api/oauth2/token");
	List<NameValuePair> nvp = new ArrayList<NameValuePair>();
	nvp.add(new BasicNameValuePair("client_id", Bot.getInstance().getApiKeys().get("dashboardid")));
	nvp.add(new BasicNameValuePair("client_secret", Bot.getInstance().getApiKeys().get("dashboardsecret")));
	nvp.add(new BasicNameValuePair("grant_type", "authorization_code"));
	nvp.add(new BasicNameValuePair("code", token));

	post.setEntity(new UrlEncodedFormEntity(nvp));

	String accessToken;
	CloseableHttpResponse response = httpclient.execute(post);
	try {
		System.out.println(response.getStatusLine());
		HttpEntity entity = response.getEntity();
		JsonObject authJson;
		try(BufferedReader buffer = new BufferedReader(new InputStreamReader(entity.getContent()))) {
			authJson = Json.parse(buffer.lines().collect(Collectors.joining("\n"))).asObject();
		}
		accessToken = authJson.getString("access_token", "");
		EntityUtils.consume(entity);
		getGuilds(res, accessToken);
	} finally {
		response.close();
	}
}
 
Example 14
Project: DiscordDevRant   File: DevRant.java   View source code 5 votes vote down vote up
/**
 * Make a GET-request to the devRant server.
 *
 * @param url The url to make the request to.
 * @return A {@link JsonObject} containing the response.
 */
JsonObject get(String url, NameValuePair... params) {
    StringBuilder finalUrl = new StringBuilder(url).append('?');
    List<NameValuePair> paramList = getParameters(params);

    // Add all parameters.
    try {
        for (NameValuePair param : paramList)
            finalUrl.append('&').append(param.getName()).append('=').append(URLEncoder.encode(param.getValue(), "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        // This never happens.
        LOGGER.error("Unsupported encoding while trying to encode parameter value.", e);
    }

    return executeRequest(Request.Get(BASE_URL + finalUrl.toString()));
}
 
Example 15
Project: marklogic-rdf4j   File: ConnectedRESTQA.java   View source code 5 votes vote down vote up
public static void detachForest(String dbName, String fName){
	try{
		DefaultHttpClient client = new DefaultHttpClient();

		client.getCredentialsProvider().setCredentials(
				new AuthScope(host, 8002),
				new UsernamePasswordCredentials("admin", "admin"));

		HttpPost post = new HttpPost("http://"+host+":8002"+ "/manage/v2/forests/"+fName);
		//			
		List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
		urlParameters.add(new BasicNameValuePair("state", "detach"));
		urlParameters.add(new BasicNameValuePair("database", dbName));

		post.setEntity(new UrlEncodedFormEntity(urlParameters));

		HttpResponse response = client.execute(post);
		HttpEntity respEntity = response.getEntity();

		if (respEntity != null) {
			// EntityUtils to get the response content
			String content =  EntityUtils.toString(respEntity);
			System.out.println(content);
		}
	}catch (Exception e) {
		// writing error to Log
		e.printStackTrace();
	}	
}
 
Example 16
Project: Java_Good   File: HttpSession.java   View source code 5 votes vote down vote up
public boolean login (String username, String password) throws IOException {
   HttpPost post = new HttpPost(app.getProperty("web.baseUrl") + "/login.php");
   List<NameValuePair> params = new ArrayList<>();
   params.add(new BasicNameValuePair("username", username));
   params.add(new BasicNameValuePair("password", password));
   params.add(new BasicNameValuePair("secure_session", "on"));
   params.add(new BasicNameValuePair("return", "index.php"));
   post.setEntity(new UrlEncodedFormEntity(params));
   CloseableHttpResponse response = httpclient.execute(post);
   String body = geTextFrom(response);
   return body.contains(String.format("<span class=\"italic\">%s</span", username));
}
 
Example 17
Project: slacklet   File: SlackWebSocketSessionImpl.java   View source code 5 votes vote down vote up
@Override
public SlackPersona.SlackPresence getPresence(SlackPersona persona) {
    HttpClient client = getHttpClient();
    HttpPost request = new HttpPost("https://slack.com/api/users.getPresence");
    List<NameValuePair> nameValuePairList = new ArrayList<>();
    nameValuePairList.add(new BasicNameValuePair("token", authToken));
    nameValuePairList.add(new BasicNameValuePair("user", persona.getId()));
    try
    {
        request.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
        HttpResponse response = client.execute(request);
        String jsonResponse = consumeToString(response.getEntity().getContent());
        LOGGER.debug("PostMessage return: " + jsonResponse);
        JsonObject resultObject = parseObject(jsonResponse);
        //quite hacky need to refactor this
        SlackUserPresenceReply reply = (SlackUserPresenceReply)SlackJSONReplyParser.decode(resultObject,this);
        if (!reply.isOk())
        {
            return SlackPersona.SlackPresence.UNKNOWN;
        }
        String presence = resultObject.get("presence") != null ? resultObject.get("presence").getAsString() : null;

        if ("active".equals(presence))
        {
            return SlackPersona.SlackPresence.ACTIVE;
        }
        if ("away".equals(presence))
        {
            return SlackPersona.SlackPresence.AWAY;
        }
    }
    catch (Exception e)
    {
        // TODO : improve exception handling
        e.printStackTrace();
    }
    return SlackPersona.SlackPresence.UNKNOWN;
}
 
Example 18
Project: appinventor-extensions   File: GameClient.java   View source code 5 votes vote down vote up
private void postLeaveInstance() {
  AsyncCallbackPair<JSONObject> setInstanceCallback = new AsyncCallbackPair<JSONObject>(){
    public void onSuccess(final JSONObject response) {
      SetInstance("");
      processInstanceLists(response);
      FunctionCompleted("LeaveInstance");
    }
    public void onFailure(final String message) {
      WebServiceError("LeaveInstance", message);
    }
  };

  postCommandToGameServer(LEAVE_INSTANCE_COMMAND,
      Lists.<NameValuePair>newArrayList(
          new BasicNameValuePair(GAME_ID_KEY, GameId()),
          new BasicNameValuePair(INSTANCE_ID_KEY, InstanceId()),
          new BasicNameValuePair(PLAYER_ID_KEY, UserEmailAddress())),
          setInstanceCallback);
}
 
Example 19
Project: mumu   File: HttpClientUtil.java   View source code 5 votes vote down vote up
/**
 * httpClient post 获取资源
 * @param url
 * @param params
 * @return
 */
public static String post(String url, Map<String, Object> params) {
	log.info(url);
	try {
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		HttpPost httpPost = new HttpPost(url);
		if (params != null && params.size() > 0) {
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			Set<String> keySet = params.keySet();
			for (String key : keySet) {
				Object object = params.get(key);
				nvps.add(new BasicNameValuePair(key, object==null?null:object.toString()));
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
		}
		CloseableHttpResponse response = httpClient.execute(httpPost);
		return EntityUtils.toString(response.getEntity(), "UTF-8");
	} catch (Exception e) {
		log.error(e);
	}
	return null;
}
 
Example 20
Project: lams   File: BasicNameValuePair.java   View source code 5 votes vote down vote up
@Override
public boolean equals(final Object object) {
    if (this == object) return true;
    if (object instanceof NameValuePair) {
        BasicNameValuePair that = (BasicNameValuePair) object;
        return this.name.equals(that.name)
              && LangUtils.equals(this.value, that.value);
    } else {
        return false;
    }
}
 
Example 21
Project: Cognizant-Intelligent-Test-Scripter   File: Entry.java   View source code 5 votes vote down vote up
public JSONArray getParams(ResourceTimings e) {
    JSONArray paramList = new JSONArray();
    try {
        List<NameValuePair> params = URLEncodedUtils.parse(new URI(e.name), "UTF-8");
        for (NameValuePair pair : params) {
            JSONObject jsonPair = new JSONObject();
            jsonPair.put("name", pair.getName());
            jsonPair.put("value", pair.getValue());
            paramList.add(jsonPair);
        }

    } catch (Exception ex) {
        return paramList;
    }
    return paramList;
}
 
Example 22
Project: Codeforces   File: HttpClientStack.java   View source code 5 votes vote down vote up
@SuppressWarnings("unused")
private static List<NameValuePair> getPostParameterPairs(Map<String, String> postParams) {
    List<NameValuePair> result = new ArrayList<NameValuePair>(postParams.size());
    for (String key : postParams.keySet()) {
        result.add(new BasicNameValuePair(key, postParams.get(key)));
    }
    return result;
}
 
Example 23
Project: boohee_v5.6   File: AuthorizeHelper.java   View source code 5 votes vote down vote up
protected static String getAccessTokenByRefreshToken(Context context, String refreshToken,
                                                     long clientId, String clientSecret,
                                                     String redirectUri, String tokenType,
                                                     String macKey, String macAlgorithm)
        throws IOException {
    List<NameValuePair> params = new ArrayList();
    params.add(new BasicNameValuePair(Constants.PARAM_CLIENT_ID, String.valueOf(clientId)));
    params.add(new BasicNameValuePair("grant_type", "refresh_token"));
    params.add(new BasicNameValuePair("client_secret", clientSecret));
    params.add(new BasicNameValuePair("token_type", SocializeProtocolConstants
            .PROTOCOL_KEY_MAC));
    params.add(new BasicNameValuePair("redirect_uri", redirectUri));
    params.add(new BasicNameValuePair("refresh_token", refreshToken));
    params.add(new BasicNameValuePair("token_type", tokenType));
    params.add(new BasicNameValuePair("mac_key", macKey));
    params.add(new BasicNameValuePair("mac_algorithm", macAlgorithm));
    String result = Network.downloadXml(context, new URL(generateUrl(TOKEN_PATH, params)));
    if (TextUtils.isEmpty(result)) {
        return result;
    }
    return result.replace(HEADER_FLAG, "");
}
 
Example 24
Project: poloniex-api-java   File: PoloniexTradingAPIClient.java   View source code 5 votes vote down vote up
@Override
public String cancelOrder(String orderNumber)
{
    List<NameValuePair> additionalPostParams = new ArrayList<>();
    additionalPostParams.add(new BasicNameValuePair("orderNumber", orderNumber));
    return returnTradingAPICommandResults("cancelOrder", additionalPostParams);
}
 
Example 25
Project: ZZUWlanConnector   File: ZZUWlanConnector.java   View source code 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
	Container container = getContentPane();
	if (e.getActionCommand().equals("��¼")) {
		String uid = username.getText().toString();
		String upw = password.getText().toString();
		String ver6 = code.getText().toString();
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("uid", uid));
		params.add(new BasicNameValuePair("upw", upw));
		params.add(new BasicNameValuePair("ver6", ver6));
		params.add(new BasicNameValuePair("pos_6", "rj"));
		message.setText("��������....");
		try {
			String str = send(url, params, "GB2312");
			byte[] b = str.getBytes();
			String s = new String(b, "gb2312");
			System.out.println(s);
			isConnection(s);
			
		} catch (Exception e1) {
			e1.printStackTrace();
		} 
		System.out.println("��¼��ť�����....");
		
		System.out.println("uid:" + uid + ",upw:" + upw + "ver6:" + ver6);
	}

}
 
Example 26
Project: smn-sdk-java   File: ListSmsCallbackEventRequest.java   View source code 5 votes vote down vote up
/**
 * obtain the get request param
 *
 * @return the param string
 */
private String getRequestParamString() {
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    if (!StringUtils.isBlank(eventType)) {
        nameValuePairs.add(new BasicNameValuePair(SmnConstants.EVENT_TYPE, eventType));
    }

    String param = "";
    if (!nameValuePairs.isEmpty()) {
        try {
            param = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs, Charset.forName("UTF-8")));
        } catch (IOException e) {
            throw new RuntimeException("get request param error");
        }
    }
    return param;
}
 
Example 27
Project: bubichain-sdk-java   File: RequestUtils.java   View source code 5 votes vote down vote up
public static List<NameValuePair> createQueryParameters(Properties queryParams){
    if (queryParams == null || queryParams.size() == 0) {
        return Collections.EMPTY_LIST;
    }
    List<NameValuePair> params = new ArrayList<NameValuePair>();

    for (String propName : queryParams.stringPropertyNames()) {
        params.add(new BasicNameValuePair(propName, queryParams.getProperty(propName)));
    }
    return params;
}
 
Example 28
Project: Huochexing12306   File: HttpUtil.java   View source code 5 votes vote down vote up
public boolean post(String url, String jsonMessage) throws ClientProtocolException, IOException {
    List<NameValuePair> lstParams = new ArrayList<NameValuePair>();
    try {
        jsonMessage = mEncrypter.encrypt(jsonMessage);
        lstParams.add(new BasicNameValuePair("message", jsonMessage));
        responseStr = httpHelper.post(null, url, lstParams);
        if (responseStr == null || responseStr.equals("")) {
            return false;
        } else {
            responseStr = mEncrypter.decrypt(responseStr);
            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
 
Example 29
Project: pay4j   File: DefaultRequestExecutor.java   View source code 5 votes vote down vote up
@Override
public FanmeiResponse get(String url, List<NameValuePair> params, Charset charset) throws RequestException {
    try {
        String str = EntityUtils.toString(new UrlEncodedFormEntity(params, charset));
        return get(url + "?" + str);
    } catch (Exception e) {
        logger.error("params=" + JSON.toJSONString(params), e);
        throw RequestException.of(e);
    }
}
 
Example 30
Project: xvms   File: SiteActions.java   View source code 5 votes vote down vote up
/**
 * 获取当前登陆账号后台权限所有栏目列表
 *
 */
public String getWebCategory() throws Exception{
	List <NameValuePair> nvps = new ArrayList <NameValuePair>();
       //网页post参数 http://www.xxx.com/appqy_api/api.php?api_key=AaPpQqYyCcOoMmLl&opt=getCategory
       nvps.add(new BasicNameValuePair("api_key", WEB_KEY));
       nvps.add(new BasicNameValuePair("opt", "getCategory"));
       
       return ht.doPost(WEB_PATH,nvps,CookieStatus);
}
 
Example 31
Project: java-bitbankcc   File: Bitbankcc.java   View source code 5 votes vote down vote up
public Orders getActiveOrders(CurrencyPair pair, Map<String, Long> option) throws BitbankException, IOException {
    String path = "/v1/user/spot/active_orders";
    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
    nameValuePair.add(new BasicNameValuePair("pair", pair.getCode()));
    for(Map.Entry<String, Long> e : option.entrySet()) {
        nameValuePair.add(new BasicNameValuePair(e.getKey(), e.getValue().toString()));
    }
    URIBuilder builder = getPrivateUriBuilder(path).setParameters(nameValuePair);
    OrdersResponse result = doHttpGet(builder, OrdersResponse.class, getPrivateRequestHeader(path, nameValuePair));
    return result.data;
}
 
Example 32
Project: poloniex-api-java   File: PoloniexTradingAPIClient.java   View source code 5 votes vote down vote up
private String trade(String tradeType, String currencyPair, BigDecimal rate, BigDecimal amount, boolean fillOrKill, boolean immediateOrCancel, boolean postOnly)
{
    List<NameValuePair> additionalPostParams = new ArrayList<>();
    additionalPostParams.add(new BasicNameValuePair("currencyPair", currencyPair));
    additionalPostParams.add(new BasicNameValuePair("rate", rate.toPlainString()));
    additionalPostParams.add(new BasicNameValuePair("amount", amount.toPlainString()));
    additionalPostParams.add(new BasicNameValuePair("fillOrKill", fillOrKill ? "1" : "0"));
    additionalPostParams.add(new BasicNameValuePair("immediateOrCancel", immediateOrCancel ? "1" : "0"));
    additionalPostParams.add(new BasicNameValuePair("postOnly", postOnly ? "1" : "0"));
    return returnTradingAPICommandResults(tradeType, additionalPostParams);
}
 
Example 33
Project: lams   File: URIBuilder.java   View source code 5 votes vote down vote up
/**
 * Sets parameter of URI query overriding existing value if set. The parameter name and value
 * are expected to be unescaped and may contain non ASCII characters.
 */
public URIBuilder setParameter(final String param, final String value) {
    if (this.queryParams == null) {
        this.queryParams = new ArrayList<NameValuePair>();
    }
    if (!this.queryParams.isEmpty()) {
        for (Iterator<NameValuePair> it = this.queryParams.iterator(); it.hasNext(); ) {
            NameValuePair nvp = it.next();
            if (nvp.getName().equals(param)) {
                it.remove();
            }
        }
    }
    this.queryParams.add(new BasicNameValuePair(param, value));
    this.encodedQuery = null;
    this.encodedSchemeSpecificPart = null;
    return this;
}
 
Example 34
Project: aliyunOcrSDK   File: HttpUtils.java   View source code 5 votes vote down vote up
/**
 * post form
 *
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @param bodys
 * @return
 * @throws Exception
 */
public static HttpResponse doPost(String host, String path, String method,
                                  Map<String, String> headers,
                                  Map<String, String> querys,
                                  Map<String, String> bodys)
        throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpPost request = new HttpPost(buildUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        request.addHeader(e.getKey(), e.getValue());
    }

    if (bodys != null) {
        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

        for (String key : bodys.keySet()) {
            nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
        }
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
        formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
        request.setEntity(formEntity);
    }

    return httpClient.execute(request);
}
 
Example 35
Project: Hotspot-master-devp   File: URIBuilder.java   View source code 5 votes vote down vote up
/**
 * Adds parameter to URI query. The parameter name and value are expected to be unescaped
 * and may contain non ASCII characters.
 */
public URIBuilder addParameter(final String param, final String value) {
    if (this.queryParams == null) {
        this.queryParams = new ArrayList<NameValuePair>();
    }
    this.queryParams.add(new BasicNameValuePair(param, value));
    this.encodedQuery = null;
    this.encodedSchemeSpecificPart = null;
    return this;
}
 
Example 36
Project: bboxapi-voicemail   File: VoiceMailApi.java   View source code 5 votes vote down vote up
public ApiResponse setVoiceMailSMS(NotificationState voicemail, NotificationState missedCall, String phoneNumber) {

        try {
            HttpPost stateRequest = new HttpPost(VOICEMAIL_NOTIFICATION_URI);

            List<NameValuePair> params = new ArrayList<NameValuePair>();

            params.add(new BasicNameValuePair("command", "Activer_Mode_SMS"));
            params.add(new BasicNameValuePair("uid", mUserInfo.getUid()));
            params.add(new BasicNameValuePair("buttonSms", voicemail.getValue()));
            params.add(new BasicNameValuePair("buttonSmsAbs", missedCall.getValue()));
            params.add(new BasicNameValuePair("numSms", phoneNumber));
            params.add(new BasicNameValuePair("Valider", "VALIDER"));

            stateRequest.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

            HttpResponse response = executeRequest(stateRequest);

            return new ApiResponse(HttpStatus.gethttpStatus(response.getStatusLine().getStatusCode()));

        } catch (UnsupportedEncodingException e) {
        }
        return new ApiResponse(HttpStatus.UNKNOWN);
    }
 
Example 37
Project: ts-benchmark   File: InfluxDB.java   View source code 5 votes vote down vote up
@Override
public Status selectMinByDeviceAndSensor(String deviceCode, String sensorCode, Date startTime, Date endTime) {
	HttpClient hc = getHttpClient();
	HttpPost post = new HttpPost(QUERY_URL);
	HttpResponse response = null;
	long costTime = 0L;
	try {
		List<NameValuePair> nameValues = new ArrayList<NameValuePair>();
		String selectSql = "SELECT MIN(value) FROM sensor where device_code='" + deviceCode + "' and sensor_code='"
				+ sensorCode + "' and time>=" + TimeUnit.MILLISECONDS.toNanos(startTime.getTime()) + " and time<=" + TimeUnit.MILLISECONDS.toNanos(endTime.getTime());
		NameValuePair nameValue = new BasicNameValuePair("q", selectSql);
		//System.out.println(selectSql);
		nameValues.add(nameValue);
		HttpEntity entity = new UrlEncodedFormEntity(nameValues, "utf-8");
		post.setEntity(entity);
		long startTime1 = System.nanoTime();
		response = hc.execute(post);
		long endTime1 = System.nanoTime();
		costTime = endTime1 - startTime1;
		//System.out.println(response);
	} catch (Exception e) {
		e.printStackTrace();
		return Status.FAILED(-1);
	}finally{
		closeResponse(response);
		closeHttpClient(hc);
	}
	//System.out.println("此次查询消耗时间[" + costTime / 1000 + "]s");
	return Status.OK(costTime);
}
 
Example 38
Project: dcits-report   File: UserService.java   View source code 5 votes vote down vote up
/**
 * 登陆报工系统
 */
public boolean login() {
	HttpPost post = new HttpPost(Api.loginUrl);
	List<NameValuePair> params = new ArrayList<NameValuePair>();
	params.add(new BasicNameValuePair("username", SessionUtil.getUsername()));
	params.add(new BasicNameValuePair("password", SessionUtil.getPassword()));
	try {
		post.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
		HttpResponse resp = client.execute(post);// 登陆
		String charset = HttpHeaderUtil.getResponseCharset(resp);
		String respHtml = StringUtil.removeEmptyLine(resp.getEntity().getContent(), charset == null ? "utf-8" : charset);

		Document doc = Jsoup.parse(respHtml);
		Elements titles = doc.getElementsByTag("TITLE");
		for (Element title : titles) {
			if (title.hasText() && title.text().contains("Success")) {
				return true;// 登陆成功
			}
		}
	} catch (Exception e) {
		logger.error("登陆失败:", e);
	}
	return false;
}
 
Example 39
Project: marathonv5   File: JavaProfile.java   View source code 5 votes vote down vote up
private String findValueOf(List<NameValuePair> values, String name) {
    for (NameValuePair nameValuePair : values) {
        if (nameValuePair.getName().equals(name)) {
            return replaceEnviron(nameValuePair.getValue());
        }
    }
    throw new RuntimeException("Could not find value for " + name + " in " + values);
}
 
Example 40
Project: Huochexing12306   File: A6Util.java   View source code 5 votes vote down vote up
public static A6Info getQueueCount(BookingInfo bInfo){
	String url = "https://kyfw.12306.cn/otn/confirmPassenger/getQueueCount";
	List<NameValuePair> lstParams = new ArrayList<NameValuePair>();
	lstParams.add(new BasicNameValuePair("train_date", bInfo.getOrder_train_date()));
	lstParams.add(new BasicNameValuePair("train_no", bInfo.getTrain_no()));
	lstParams.add(new BasicNameValuePair("stationTrainCode", bInfo.getStationTrainCode()));
	lstParams.add(new BasicNameValuePair("seatType", bInfo.getSeatType()));
	lstParams.add(new BasicNameValuePair("fromStationTelecode", bInfo.getFromStationTelecode()));
	lstParams.add(new BasicNameValuePair("toStationTelecode", bInfo.getToStationTelecode()));
	lstParams.add(new BasicNameValuePair("leftTicket", bInfo.getLeftTicket()));
	lstParams.add(new BasicNameValuePair("purpose_codes", bInfo.getOrder_purpose_codes()));
	lstParams.add(new BasicNameValuePair("_json_att", ""));
	lstParams.add(new BasicNameValuePair("REPEAT_SUBMIT_TOKEN", bInfo.getRepeatSubmitToken()));
	try{
		A6Info a6Json = post(bInfo, null, url, lstParams);
		return a6Json;
	}catch(Exception e){
		e.printStackTrace();
	}
	return null;
}