private synchronized void PostParam(String url, List<BasicNameValuePair> parameters) throws Exception { HttpPost post = new HttpPost(url); String result = ""; try { post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8")); HttpResponse response = client.execute(post); HttpEntity httpEntity = response.getEntity(); result = EntityUtils.toString(httpEntity, "utf-8"); } catch (java.io.IOException e) { e.printStackTrace(); } finally { JSONObject jsonObject = new JSONObject(result); String status = jsonObject.getString("status"); if (!status.equals("success")) { throw new Exception(jsonObject.getString("msg")); } System.out.println(status); } }
public Map<String, String> connect(String url, Map<String, Object> parameters) throws ManagerResponseException { Map<String, String> response = new HashMap<String, String>(); CloseableHttpClient httpclient = HttpClients.createDefault(); List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair("j_username", (String) parameters.get("login"))); nvps.add(new BasicNameValuePair("j_password", (String) parameters.get("password"))); localContext = HttpClientContext.create(); localContext.setCookieStore(new BasicCookieStore()); HttpPost httpPost = new HttpPost(url); try { httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse httpResponse = httpclient.execute(httpPost, localContext); ResponseHandler<String> handler = new CustomResponseErrorHandler(); String body = handler.handleResponse(httpResponse); response.put(BODY, body); httpResponse.close(); } catch (Exception e) { authentificationUtils.getMap().clear(); throw new ManagerResponseException(e.getMessage(), e); } return response; }
/** * 报工 * */ public boolean report() { HttpPost post = new HttpPost(Api.reportUrl); try { post.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8)); HttpResponse resp = client.execute(post); JSONObject jo = JSONObject.parseObject(EntityUtils.toString(resp.getEntity())); // 报工成功,返回json结构的报文{"data" : [ {},{}...],"success" : true} if (jo.getBooleanValue("success")) { return true; } logger.warn(jo.getString("error")); } catch (Exception e) { logger.error("报工异常:", e); } return false; }
/** * 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"); request.setEntity(formEntity); } return httpClient.execute(request); }
public String call(final String vast, final String adid, final String zoneid) { final List<NameValuePair> nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair("adid", adid)); nameValuePairs.add(new BasicNameValuePair("zoneid", zoneid)); nameValuePairs.add(new BasicNameValuePair("vast", vast)); try { return jsonPostConnector.connect(new UrlEncodedFormEntity(nameValuePairs, StandardCharsets.UTF_8), new HttpPost(endPoint)); } catch (final BidProcessingException e) { log.error(e.getMessage()); } return null; }
/** * 登陆报工系统 */ 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 void sendPost(String url, String urlParameters) throws Exception { HttpClient client = getHttpClient(); HttpPost request = new HttpPost(url); request.addHeader("User-Agent", "Mozilla/5.0"); List<NameValuePair> valuePairs = new ArrayList<NameValuePair>(); String[] s = urlParameters.split("&"); for (int i = 0; i < s.length; i++) { String g = s[i]; valuePairs.add(new BasicNameValuePair(g.substring(0,g.indexOf("=")), g.substring(g.indexOf("=")+1))); } request.setEntity(new UrlEncodedFormEntity(valuePairs)); HttpResponse response = client.execute(request); System.out.println("Response Code: " + response.getStatusLine().getStatusCode()); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String responseLine; while ((responseLine = bufferedReader.readLine()) != null) { result.append(responseLine); } System.out.println("Response: " + result.toString()); }
public static Future<HttpResponse> POST(String url, FutureCallback<HttpResponse> callback, List<NameValuePair> params, String encoding, Map<String, String> headers) { HttpPost post = new HttpPost(url); headers.forEach((key, value) -> { post.setHeader(key, value); }); HttpEntity entity = new UrlEncodedFormEntity(params, HttpClientUtil.getEncode(encoding)); post.setEntity(entity); return HTTP_CLIENT.execute(post, callback); }
private String post(String url, List<NameValuePair> nvps) throws IOException{ CloseableHttpClient httpclient = connectionPoolManage.getHttpClient(); HttpPost httpPost = new HttpPost(url); if(nvps != null) httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); CloseableHttpResponse response = httpclient.execute(httpPost); String result = null; if(response.getStatusLine().getStatusCode() == 200){ HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity); } httpclient.close(); return result; }
/** * Creates a module for a specific customer * * @param customerName the name of the customer * @param moduleName the name of the module to create * @return request object to check status codes and return values */ public Response createModule( String customerName, String moduleName ) { final HttpPost request = new HttpPost( this.yambasBase + "customers/" + customerName + "/modules" ); setAuthorizationHeader( request ); final List<NameValuePair> data = new ArrayList<NameValuePair>( ); data.add( new BasicNameValuePair( "name", moduleName ) ); try { request.setEntity( new UrlEncodedFormEntity( data ) ); final HttpResponse response = this.client.execute( request ); return new Response( response ); } catch ( final IOException e ) { e.printStackTrace( ); } return null; }
@Override public void run() { try { BasicHttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 500); HttpConnectionParams.setSoTimeout(httpParams, 500); HttpClient httpclient = new DefaultHttpClient(httpParams); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("latitude", "" + latitude)); params.add(new BasicNameValuePair("longitude", "" + longitude)); params.add(new BasicNameValuePair("userid", userId)); //服务器地址,指向Servlet HttpPost httpPost = new HttpPost(ServerUtil.SLUpdateLocation); final UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");//以UTF-8格式发送 httpPost.setEntity(entity); //对提交数据进行编码 httpclient.execute(httpPost); } catch (Exception e) { } }
private void postSlackCommand(Map<String, String> params, String command, SlackMessageHandleImpl handle) { HttpClient client = getHttpClient(); HttpPost request = new HttpPost(SLACK_API_HTTPS_ROOT + command); List<NameValuePair> nameValuePairList = new ArrayList<>(); for (Map.Entry<String, String> arg : params.entrySet()) { nameValuePairList.add(new BasicNameValuePair(arg.getKey(), arg.getValue())); } try { request.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8")); HttpResponse response = client.execute(request); String jsonResponse = consumeToString(response.getEntity().getContent()); LOGGER.debug("PostMessage return: " + jsonResponse); ParsedSlackReply reply = SlackJSONReplyParser.decode(parseObject(jsonResponse),this); handle.setReply(reply); } catch (Exception e) { // TODO : improve exception handling e.printStackTrace(); } }
private void useHttpClientPost(String url) { HttpPost mHttpPost = new HttpPost(url); mHttpPost.addHeader("Connection", "Keep-Alive"); try { HttpClient mHttpClient = createHttpClient(); List<NameValuePair> postParams = new ArrayList<>(); //要传递的参数 postParams.add(new BasicNameValuePair("ip", "59.108.54.37")); mHttpPost.setEntity(new UrlEncodedFormEntity(postParams)); HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost); HttpEntity mHttpEntity = mHttpResponse.getEntity(); int code = mHttpResponse.getStatusLine().getStatusCode(); if (null != mHttpEntity) { InputStream mInputStream = mHttpEntity.getContent(); String respose = converStreamToString(mInputStream); Log.d(TAG, "请求状态码:" + code + "\n请求结果:\n" + respose); mInputStream.close(); } } catch (IOException e) { e.printStackTrace(); } }
@SuppressWarnings("unchecked") private HttpEntity createDataEntity(Object data) { try { if (data instanceof Map) { List<NameValuePair> params = new ArrayList<NameValuePair>(0); for (Entry<String, Object> entry : ((Map<String, Object>) data).entrySet()) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString())); } return new UrlEncodedFormEntity(params, "UTF-8"); } else { return new StringEntity(data.toString(), "UTF-8"); } } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unsupported encoding noticed. Error message: " + e.getMessage()); } }
/** * Implemented createPOST from Interface interfaceAPI (see for more details) * * @param message * Message, which should be posted. * @throws UnsupportedEncodingException * if text is not in Unicode */ public void createPOST(String message) throws UnsupportedEncodingException { httpclient = HttpClients.createDefault(); httppost = new HttpPost(Configuration.meaningcloudApiUri); // Request parameters and other properties. List<NameValuePair> params = new ArrayList<NameValuePair>(3); params.add(new BasicNameValuePair("txt", message)); params.add(new BasicNameValuePair("key", apiKey)); params.add(new BasicNameValuePair("of", outputMode)); params.add(new BasicNameValuePair("lang", lang)); params.add(new BasicNameValuePair("tt", topictypes)); httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); }
public static String resetPwd(int user_id, String pwd) throws Exception { HttpClient task_post = new DefaultHttpClient(); HttpPost post = new HttpPost(url + "/ResetPwd"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("user_id", String.valueOf(user_id))); params.add(new BasicNameValuePair("pwd", pwd)); post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse response = task_post.execute(post); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String result = null; HttpEntity httpEntity = response.getEntity(); if (httpEntity != null) { result = EntityUtils.toString(httpEntity); } JSONObject jsonObject = new JSONObject(result); int pwd_reset = jsonObject.getInt("pwd_reset"); if (pwd_reset == 1) return "SUCCESS"; else return "FAIL"; } return "401 UNAUTHORIZED"; }
/** * <p>根据URL和参数创建HttpPost对象</p> * * @param url * @param paramMap * @return */ public static HttpPost createHttpPost(String url, Map<String,String> paramMap){ try { HttpPost httpPost = new HttpPost(url); if(paramMap != null && !paramMap.isEmpty()){ List<NameValuePair> params = new ArrayList<NameValuePair>(); for(Map.Entry<String, String> entry : paramMap.entrySet()){ params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, DEFAULT_CHARSET); httpPost.setEntity(formEntity); } return httpPost; } catch (Exception e) { logger.error(e.getMessage()); throw new HttpClientException(e.getMessage(), e); } }
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); } }
/** * Adds the module to the app * * @param customerName * the name of the customer which owns the app * @param appName * the name of the app * @param moduleName * the name of the module to add * @return request object to check status codes and return values */ public Response addModuleToApp( String customerName, String appName, String moduleName ) { HttpPost request = new HttpPost( this.yambasBase + "customers/" + customerName + "/apps/" + appName + "/usedmodules" ); setAuthorizationHeader( request ); request.addHeader( "x-apiomat-system", this.system.toString( ) ); final List<NameValuePair> data = new ArrayList<NameValuePair>( ); data.add( new BasicNameValuePair( "moduleName", moduleName ) ); try { request.setEntity( new UrlEncodedFormEntity( data ) ); final HttpResponse response = this.client.execute( request ); return new Response( response ); } catch ( final IOException e ) { e.printStackTrace( ); } return null; }
public String update_online_time(int machine_id, int user_id, int delta) throws Exception { HttpClient task_post = new DefaultHttpClient(); HttpPost post = new HttpPost(url + "/update_online_time"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("machine_id", String.valueOf(machine_id))); params.add(new BasicNameValuePair("user_id", String.valueOf(user_id))); params.add(new BasicNameValuePair("delta", String.valueOf(delta))); post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse response = task_post.execute(post); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 权限通过 return "AUTHORIZED"; } return "401 UNAUTHORIZED"; }
/** * 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; }
private Token getAccessToken(@NotNull String code) throws IOException { // Initialize client HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost(TOKEN_URL); // add request parameters List<NameValuePair> parameters = new ArrayList<>(); parameters.add(new BasicNameValuePair("code", code)); parameters.add(new BasicNameValuePair("client_id", CLIENT_ID)); parameters.add(new BasicNameValuePair("client_secret", CLIENT_SECRET)); parameters.add(new BasicNameValuePair("redirect_uri", REDIRECT_URI)); parameters.add(new BasicNameValuePair("grant_type", GRANT_TYPE)); httpPost.setEntity(new UrlEncodedFormEntity(parameters)); // send request org.apache.http.HttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); InputStream inputStream = response.getEntity().getContent(); if (HttpUtilities.success(statusCode)) return gson.fromJson(new InputStreamReader(inputStream), Token.class); throw new ApiException(HttpStatus.valueOf(statusCode)); }
@Override public Status selectAvgByDeviceAndSensor(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 MEAN(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); }
/** * 构建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; }
@Deprecated public static String post(String Url, List<NameValuePair> params) { String strResult = null; HttpResponse httpResponse; HttpPost httpRequest = new HttpPost(Url); try { httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); httpResponse = new DefaultHttpClient().execute(httpRequest); if (httpResponse.getStatusLine().getStatusCode() == 200) { strResult = EntityUtils.toString(httpResponse.getEntity()); } } catch (Exception e) { e.printStackTrace(); } return strResult; }
public String postHttp(String url, List<NameValuePair> params, List<NameValuePair> headers) throws IOException { HttpPost post = new HttpPost(url); post.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8)); post.getEntity().toString(); if (headers != null) { for (NameValuePair header : headers) { post.addHeader(header.getName(), header.getValue()); } } HttpClient httpClient = HttpClientBuilder.create().build(); HttpResponse response = httpClient.execute(post); HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toString(entity); } return null; }
public String executePost(List<NameValuePair> urlParameters) throws Exception { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(this.url); post.setHeader("User-Agent", USER_AGENT); post.setEntity(new UrlEncodedFormEntity(urlParameters)); HttpResponse response = client.execute(post); BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { result.append(line); } return result.toString(); }
/** * Update a subscription to a group given a blank {@link Subscription} * object with only the updated * fields set. * Example: * * <pre> * final Subscription subToUpdate = new Subscription(); * subToUpdate.setAutoFollowReplies(true); * final Subscription updateSub = client.member().updateMember(subToUpdate); * </pre> * * @param subscription * - with only the updated fields set * @return the full {@link Subscription} after a successful update * @throws URISyntaxException * @throws IOException * @throws GroupsIOApiException */ public Subscription updateMember(final Subscription subscription) throws URISyntaxException, IOException, GroupsIOApiException { if (apiClient.group().getPermissions(subscription.getGroupId()).getManageMemberSubscriptionOptions()) { final URIBuilder uri = new URIBuilder().setPath(baseUrl + "updatemember"); final HttpPost request = new HttpPost(); final Map<String, Object> map = OM.convertValue(subscription, Map.class); final List<BasicNameValuePair> postParameters = new ArrayList<>(); for (final Entry<String, Object> entry : map.entrySet()) { postParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString())); } request.setEntity(new UrlEncodedFormEntity(postParameters)); request.setURI(uri.build()); return callApi(request, Subscription.class); } else { final Error error = new Error(); error.setType(GroupsIOApiExceptionType.INADEQUATE_PERMISSIONS); throw new GroupsIOApiException(error); } }
/** * 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; }
private HttpResponse getPostResponse(String apiUrl, HttpPost httpPost) throws IOException { try{ List<NameValuePair> nvps = new ArrayList<NameValuePair>(); String[] urlAndParame = apiUrl.split("\\?"); String apiUrlNoParame = urlAndParame[0]; Map<String, String> parameMap = StrUtil.splitUrlToParameMap(apiUrl); nvps = paramsConverter(parameMap); httpPost.setURI(new URI(apiUrlNoParame)); if(reqHeader != null) { Iterator<String> iterator = reqHeader.keySet().iterator(); while(iterator.hasNext()) { String key = iterator.next(); httpPost.addHeader(key, reqHeader.get(key)); } } httpPost.setEntity(new UrlEncodedFormEntity(nvps, postDataEncode)); return httpClient.execute(httpPost); }catch(Exception e){ throw new IllegalStateException(e); } }
/** * Send DanMu. * * @param color color of DanMu * @param fontSize font size of DanMu * @param mode DanMu mode * @param message DanMu content * @return server response entity */ public DanMuResponseEntity send(String color, String fontSize, String mode, String message) throws IOException, IllegalArgumentException { resolveRoomData(); CloseableHttpClient closeableHttpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://live.bilibili.com/msg/send"); httpPost.setHeader("Cookie", cookies); httpPost.setEntity( new UrlEncodedFormEntity( Arrays.asList( new BasicNameValuePair("color", color), new BasicNameValuePair("fontsize", fontSize), new BasicNameValuePair("mode", mode), new BasicNameValuePair("msg", message), new BasicNameValuePair("random", random.toString()), new BasicNameValuePair("roomid", roomId.toString()) ), StandardCharsets.UTF_8 ) ); DanMuResponseEntity danMuResponseEntity = JSON.parseObject(EntityUtils.toString(closeableHttpClient.execute(httpPost).getEntity()), DanMuResponseEntity.class); closeableHttpClient.close(); return danMuResponseEntity; }
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; } }
private static String httpPush (ArrayList<NameValuePair> nameValuePairs,String action) throws Exception { HttpPost httppost = new HttpPost(FLOWZR_API_URL + nsString + "/" + action + "/"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8)); HttpResponse response; String strResponse; response = http_client.execute(httppost); HttpEntity entity = response.getEntity(); int code = response.getStatusLine().getStatusCode(); BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); strResponse = reader.readLine(); entity.consumeContent(); if (code!=200) { throw new Exception(Html.fromHtml(strResponse).toString()); } return strResponse; }
/** * send current ip to server */ private String ipSend() throws Exception { HttpClient ip_send = new DefaultHttpClient(); HttpPost post = new HttpPost(url + "/UploadIP"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("machine_id", String.valueOf(machine_id))); params.add(new BasicNameValuePair("ip", ip)); post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse httpResponse = ip_send.execute(post); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String result = null; HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { result = EntityUtils.toString(httpEntity); } JSONObject jsonObject = new JSONObject(result); int ip_save = jsonObject.getInt("ip_save"); if (ip_save == 1) { return "SUCCESS"; } else return "FAIL"; } return "401 UNAUTHORIZED"; }
/** * Refreshes the OAuth2 token with a refresh token. * * @param refreshToken the refresh token * @return Token map containing an OAuth2 access token and other info */ public String refreshOauth2Token( String refreshToken ) { final HttpPost request = new HttpPost( this.yambasHost + "/yambas/oauth/token" ); final List<NameValuePair> data = new ArrayList<NameValuePair>( ); data.add( new BasicNameValuePair( "grant_type", "refresh_token" ) ); data.add( new BasicNameValuePair( "client_id", this.getAppName( ) ) ); data.add( new BasicNameValuePair( "client_secret", this.getApiKey( ) ) ); data.add( new BasicNameValuePair( "refresh_token", refreshToken ) ); try { request.setEntity( new UrlEncodedFormEntity( data ) ); final HttpResponse response = this.client.execute( request ); final String ret = EntityUtils.toString( response.getEntity( ) ); request.releaseConnection( ); return ret; } catch ( final IOException 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; }
/** * 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 void setPresence(SlackPersona.SlackPresence presence) { if(presence == SlackPersona.SlackPresence.UNKNOWN || presence == SlackPersona.SlackPresence.ACTIVE) { throw new IllegalArgumentException("Presence must be either AWAY or AUTO"); } HttpClient client = getHttpClient(); HttpPost request = new HttpPost(SLACK_API_HTTPS_ROOT + SET_PERSONA_ACTIVE); List<NameValuePair> nameValuePairList = new ArrayList<>(); nameValuePairList.add(new BasicNameValuePair("token", authToken)); nameValuePairList.add(new BasicNameValuePair("presence", presence.toString().toLowerCase())); try { request.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8")); HttpResponse response = client.execute(request); String JSONResponse = consumeToString(response.getEntity().getContent()); LOGGER.debug("JSON Response=" + JSONResponse); }catch(IOException e) { e.printStackTrace(); } }
/** * 向目标url发送post请求 * * @author sheefee * @date 2017年9月12日 下午5:10:36 * @param url * @param params * @return boolean */ public static boolean post(String url, Map<String, String> params) { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); // 参数处理 if (params != null && !params.isEmpty()) { List<NameValuePair> list = new ArrayList<NameValuePair>(); Iterator<Entry<String, String>> it = params.entrySet().iterator(); while (it.hasNext()) { Entry<String, String> entry = it.next(); list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } httpPost.setEntity(new UrlEncodedFormEntity(list, Consts.UTF_8)); } // 执行请求 try { CloseableHttpResponse response = httpclient.execute(httpPost); response.getStatusLine().getStatusCode(); } catch (Exception e) { e.printStackTrace(); } return true; }
private HttpRequestBase apiRequest(String apiMethod, List<NameValuePair> params) { HttpPost post = new HttpPost(getRestApiUrl(apiMethod)); post.setConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build()); List<NameValuePair> formFields = new ArrayList<>(); formFields.add(new BasicNameValuePair("api.token", myPassword)); formFields.addAll(params); try { post.setEntity(new UrlEncodedFormEntity(formFields, "UTF-8")); } catch (UnsupportedEncodingException ignored) { // cannot happen } return post; }