@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; }
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; }
/** * 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; }
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; } }
/** * 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(); }
/** * 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; }
/** * 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(); } }
/** * 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())); }
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); }
/** * 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; }
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; }
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, ""); }
/** * 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; }
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; }
/** * 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; }
/** * 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); }
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); }
/** * 登陆报工系统 */ 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; }
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; }
/** * Creates an app for a specific customer * * @param customerName the name of the customer * @param appName the name of the app to create * @return request object to check status codes and return values */ public Response createApp( String customerName, String appName ) { final HttpPost request = new HttpPost( this.yambasBase + "customers/" + customerName + "/apps" ); setAuthorizationHeader( request ); final List<NameValuePair> data = new ArrayList<NameValuePair>( ); data.add( new BasicNameValuePair( "name", appName ) ); try { request.setEntity( new UrlEncodedFormEntity( data ) ); final HttpResponse response = this.client.execute( request ); this.appName = appName; return new Response( response ); } catch ( final IOException e ) { e.printStackTrace( ); } return null; }
@VisibleForTesting static String getDoAs(HttpServletRequest request) { List<NameValuePair> list = URLEncodedUtils.parse(request.getQueryString(), UTF8_CHARSET); if (list != null) { for (NameValuePair nv : list) { if (DelegationTokenAuthenticatedURL.DO_AS. equalsIgnoreCase(nv.getName())) { return nv.getValue(); } } } return null; }
/** * @param paramNameValues An even number of strings indicating the parameter * names and values i.e. "param1", "value1", "param2", "value2" * @return */ @Override public String queryString(String... paramNameValues) { final List<NameValuePair> params = Lists.newArrayList(); // if( paramNameValues != null ) { if( paramNameValues.length % 2 != 0 ) { throw new RuntimeException("Must supply an even number of paramNameValues"); } for( int i = 0; i < paramNameValues.length; i += 2 ) { params.add(new BasicNameValuePair(paramNameValues[i], paramNameValues[i + 1])); } } return queryStringNv(params); }
public static String getNewNumber() throws TwilioRestException { TwilioRestClient client = new TwilioRestClient(accountSID, authToken); // Build a filter for the AvailablePhoneNumberList Map<String, String> params = new HashMap<String, String>(); params.put("SmsEnabled", "true"); AvailablePhoneNumberList numbers = client.getAccount().getAvailablePhoneNumbers(params, "US", "Local"); List<AvailablePhoneNumber> list = numbers.getPageData(); // Purchase the first number in the list. List<NameValuePair> purchaseParams = new ArrayList<NameValuePair>(); purchaseParams.add(new BasicNameValuePair("PhoneNumber", list.get(0).getPhoneNumber())); purchaseParams.add(new BasicNameValuePair("SmsUrl", "http://platform.workamerica.co/TwilioReceiverServlet")); return client.getAccount().getIncomingPhoneNumberFactory().create(purchaseParams).getPhoneNumber().substring(2); }
public boolean continuePayNoCompleteMyOrder(BookingInfo bInfo){ String url = "https://kyfw.12306.cn/otn/queryOrder/continuePayNoCompleteMyOrder"; List<NameValuePair> lstParams = new ArrayList<NameValuePair>(); lstParams.add(new BasicNameValuePair("sequence_no", mInfo.getSequence_no())); lstParams.add(new BasicNameValuePair("pay_flag", "pay")); 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()); String existError = jsonObj.optString("existError", null); if (existError == null){ return false; }else if (existError.equals("N")){ return true; } }catch(Exception e){ e.printStackTrace(); } return false; }
private void createTestDB() { HttpClient hc = getHttpClient(); HttpPost post = new HttpPost(QUERY_URL); HttpResponse response = null; try { List<NameValuePair> nameValues = new ArrayList<NameValuePair>(); String createSql = "CREATE DATABASE " + DB_NAME; NameValuePair nameValue = new BasicNameValuePair("q", createSql); nameValues.add(nameValue); HttpEntity entity = new UrlEncodedFormEntity(nameValues, "utf-8"); post.setEntity(entity); response = hc.execute(post); closeHttpClient(hc); // System.out.println(response); } catch (Exception e) { e.printStackTrace(); }finally{ closeResponse(response); closeHttpClient(hc); } }
/** * Returns a list of {@link org.apache.http.NameValuePair NameValuePairs} as parsed from the given string * using the given character encoding. * * @param s text to parse. * @param charset Encoding to use when decoding the parameters. * @since 4.2 */ public static List<NameValuePair> parse(final String s, final Charset charset) { if (s == null) { return Collections.emptyList(); } BasicHeaderValueParser parser = BasicHeaderValueParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(s.length()); buffer.append(s); ParserCursor cursor = new ParserCursor(0, buffer.length()); List<NameValuePair> list = new ArrayList<NameValuePair>(); while (!cursor.atEnd()) { NameValuePair nvp = parser.parseNameValuePair(buffer, cursor, DELIM); if (nvp.getName().length() > 0) { list.add(new BasicNameValuePair( decodeFormFields(nvp.getName(), charset), decodeFormFields(nvp.getValue(), charset))); } } return list; }
/** * 构建FormEntity * * @param formParam * @return * @throws UnsupportedEncodingException */ private static UrlEncodedFormEntity buildFormEntity(Map<String, String> formParam) throws UnsupportedEncodingException { if (formParam != null) { List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(); for (String key : formParam.keySet()) { nameValuePairList.add(new BasicNameValuePair(key, formParam.get(key))); } UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, Constants.ENCODING); formEntity.setContentType(ContentType.CONTENT_TYPE_FORM); return formEntity; } return null; }
public static Object pushDelete() throws Exception { String sql="select count(*) from " + DatabaseHelper.DELETE_LOG_TABLE ; Cursor cursorCursor=db.rawQuery(sql, null); cursorCursor.moveToFirst(); long total=cursorCursor.getLong(0); cursorCursor.close(); Cursor cursor=db.rawQuery("select table_name,remote_key from delete_log",null); int i=0; String del_list=""; if (cursor.moveToFirst()) { do { //notifyUser("push delete",(int)(Math.round(i*100/total))); del_list+=cursor.getString(1) + ";"; i++; } while (cursor.moveToNext()); ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("action","pushDelete")); nameValuePairs.add(new BasicNameValuePair("remoteKey",del_list)); httpPush(nameValuePairs,"delete"); } cursor.close(); return null; }
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); } }
public static HttpEntity makeMultipartEntity(List<NameValuePair> params, final Map<String, File> files) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //如果有SocketTimeoutException等情况,可修改这个枚举 //builder.setCharset(Charset.forName("UTF-8")); //不要用这个,会导致服务端接收不到参数 if (params != null && params.size() > 0) { for (NameValuePair p : params) { builder.addTextBody(p.getName(), p.getValue(), ContentType.TEXT_PLAIN.withCharset("UTF-8")); } } if (files != null && files.size() > 0) { Set<Entry<String, File>> entries = files.entrySet(); for (Entry<String, File> entry : entries) { builder.addPart(entry.getKey(), new FileBody(entry.getValue())); } } return builder.build(); }
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; } } }
@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()); }
/** * 获取当前登陆账号后台权限所有栏目列表 * */ 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); }
@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); }
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(); } }
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)); }
@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; }
@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; } }