Java Code Examples for org.apache.http.client.entity.UrlEncodedFormEntity

The following are top voted examples for showing how to use org.apache.http.client.entity.UrlEncodedFormEntity. 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: hack_sjtu_2017   File: HttpHandler.java   View source code 7 votes vote down vote up
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);
    }
}
 
Example 2
Project: dcits-report   File: UserService.java   View source code 7 votes vote down vote up
/**
 * 报工
 * 
 */
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;
}
 
Example 3
Project: mumu-core   File: HttpClientUtil.java   View source code 7 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 4
Project: elasticjob-stock-push   File: HttpUtils.java   View source code 6 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");

        request.setEntity(formEntity);
    }

    return httpClient.execute(request);
}
 
Example 5
Project: openssp   File: VastResolverBroker.java   View source code 6 votes vote down vote up
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;
}
 
Example 6
Project: JavaRushTasks   File: Solution.java   View source code 6 votes vote down vote up
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());
}
 
Example 7
Project: wechat-mall   File: AsynHttpClient.java   View source code 6 votes vote down vote up
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);
}
 
Example 8
Project: dubbocloud   File: MockTestFilter.java   View source code 6 votes vote down vote up
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;
}
 
Example 9
Project: integration-test-helper   File: AomHttpClient.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 10
Project: DaiGo   File: LocationService.java   View source code 6 votes vote down vote up
@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) {

    }
}
 
Example 11
Project: slacklet   File: SlackWebSocketSessionImpl.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 12
Project: android-advanced-light   File: MainActivity.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 13
Project: httpclient   File: RestClient.java   View source code 6 votes vote down vote up
@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());
	}
}
 
Example 14
Project: keywordEntityApiRankService   File: MeaningCloudAPI.java   View source code 6 votes vote down vote up
/**
 * 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"));

}
 
Example 15
Project: Higher-Cloud-Computing-Project   File: ServerUtil.java   View source code 6 votes vote down vote up
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";
    }
 
Example 16
Project: devops-cstack   File: RestUtils.java   View source code 6 votes vote down vote up
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;
    }
 
Example 17
Project: xproject   File: HttpClientUtils.java   View source code 6 votes vote down vote up
/**
   * <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);
}
  }
 
Example 18
Project: ts-benchmark   File: InfluxDB2.java   View source code 6 votes vote down vote up
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);
		}
	}
 
Example 19
Project: integration-test-helper   File: AomHttpClient.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 20
Project: Higher-Cloud-Computing-Project   File: ServerUtil.java   View source code 6 votes vote down vote up
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";
    }
 
Example 21
Project: url-to-google-drive   File: GoogleOauthController.java   View source code 6 votes vote down vote up
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));
}
 
Example 22
Project: ts-benchmark   File: InfluxDB.java   View source code 6 votes vote down vote up
@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);
}
 
Example 23
Project: quickhybrid-android   File: HttpUtil.java   View source code 6 votes vote down vote up
@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;
}
 
Example 24
Project: poloniex-api-java   File: HTTPClient.java   View source code 6 votes vote down vote up
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;
}
 
Example 25
Project: freemoz   File: HttpRequest.java   View source code 6 votes vote down vote up
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();
}
 
Example 26
Project: groupsio-api-java   File: MemberResource.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 27
Project: FCat   File: HttpCallSSL.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 28
Project: bilibili-live-api   File: LiveDanMuSender.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 29
Project: financisto1-holo   File: FlowzrSyncEngine.java   View source code 6 votes vote down vote up
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;    	    	
  }
 
Example 30
Project: Higher-Cloud-Computing-Project   File: ServerUtil.java   View source code 6 votes vote down vote up
/**
 * 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";
}
 
Example 31
Project: integration-test-helper   File: AomHttpClient.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 32
Project: elasticjob-oray-client   File: HttpUtils.java   View source code 6 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 33
Project: slacklet   File: SlackWebSocketSessionImpl.java   View source code 6 votes vote down vote up
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();
    }

}
 
Example 34
Project: simple-sso   File: HTTPUtil.java   View source code 6 votes vote down vote up
/**
 * 向目标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;
}
 
Example 35
Project: ijphab   File: PhabricatorRepository.java   View source code 6 votes vote down vote up
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;
}
 
Example 36
Project: pnc-repressurized   File: PastebinHandler.java   View source code 5 votes vote down vote up
public boolean loginInternal(String userName, String password) {
    HttpPost httppost = new HttpPost("http://pastebin.com/api/api_login.php");

    List<NameValuePair> params = new ArrayList<NameValuePair>(3);
    params.add(new BasicNameValuePair("api_dev_key", DEV_KEY));
    params.add(new BasicNameValuePair("api_user_name", userName));
    params.add(new BasicNameValuePair("api_user_password", password));
    try {
        httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            userKey = IOUtils.toString(instream, "UTF-8");
            if (userKey.startsWith("Bad API request")) {
                Log.warning("User tried to log in into pastebin, it responded with the following: " + userKey);
                userKey = null;
                return false;
            }
            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
 
Example 37
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 38
Project: webmate-sdk-java   File: WebmateApiClient.java   View source code 5 votes vote down vote up
protected HttpResponse sendPOSTUnchecked(UriTemplate schema, Map<String, String> params, List<NameValuePair> urlParams) {
    HttpResponse httpResponse;
    try {
        HttpPost req = new HttpPost(schema.buildUri(environment.baseURI, params));
        req.setEntity(new UrlEncodedFormEntity(urlParams));
        httpResponse = this.httpClient.execute(req);
        // Buffer the response entity in memory so we can release the connection safely
        HttpEntity old = httpResponse.getEntity();
        EntityUtils.updateEntity(httpResponse, new StringEntity(EntityUtils.toString(old)));
        req.releaseConnection();
    } catch (IOException e) {
        throw new WebmateApiClientException("Error sending POST to webmate API", e);
    }
    return httpResponse;
}
 
Example 39
Project: rongyunDemo   File: RequestParams.java   View source code 5 votes vote down vote up
public HttpEntity createFormEntity() {
    try {
        return new UrlEncodedFormEntity(getParamsList(), HTTP.UTF_8);
    } catch (UnsupportedEncodingException e) {
        return null; // Actually cannot happen when using utf-8
    }
}
 
Example 40
Project: pay4j   File: DefaultRequestExecutor.java   View source code 5 votes vote down vote up
@Override
public FanmeiResponse post(String url, List<NameValuePair> params, Charset charset) throws RequestException {
    HttpPost httpPost = new HttpPost(url);
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(params, charset));
        CloseableHttpResponse response = httpClient.execute(httpPost);
        return genFanmeiResponse(charset, response);
    } catch (Exception e) {
        throw RequestException.of(e);
    }
}