org.apache.http.Consts Java Examples

The following examples show how to use org.apache.http.Consts. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApiRequestService.java    From ticket with GNU General Public License v3.0 6 votes vote down vote up
public List<PassengerModel> getPassengerDTOs(String userName, String token) {
    HttpUtil httpUtil = UserTicketStore.httpUtilStore.get(userName);
    List<PassengerModel> passengerModelList = new ArrayList<>();
    HttpPost httpPost = new HttpPost(apiConfig.getGetPassengerDTOs());
    List<NameValuePair> formparams = new ArrayList<>();
    formparams.add(new BasicNameValuePair("_json_att", ""));
    formparams.add(new BasicNameValuePair("REPEAT_SUBMIT_TOKEN", token));
    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
            Consts.UTF_8);
    httpPost.setEntity(urlEncodedFormEntity);
    Gson jsonResult = new Gson();
    String response = httpUtil.post(httpPost);
    Map rsmap = jsonResult.fromJson(response, Map.class);
    if (rsmap.getOrDefault("status", "").toString().equals("true")) {
        rsmap = (Map<String, Object>) rsmap.get("data");
        List<Map<String, String>> passengers = (List<Map<String, String>>) rsmap
                .get("normal_passengers");
        if (!CollectionUtils.isEmpty(passengers)) {
            passengers.forEach(passenger -> {
                PassengerModel passengerModel = new PassengerModel(passenger);
                passengerModelList.add(passengerModel);
            });
        }
    }
    return passengerModelList;
}
 
Example #2
Source File: WechatTools.java    From xiaoV with GNU General Public License v3.0 6 votes vote down vote up
private static boolean webWxLogout() {
	String url = String.format(URLEnum.WEB_WX_LOGOUT.getUrl(), core
			.getLoginInfo().get(StorageLoginInfoEnum.url.getKey()));
	List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
	params.add(new BasicNameValuePair("redirect", "1"));
	params.add(new BasicNameValuePair("type", "1"));
	params.add(new BasicNameValuePair("skey", (String) core.getLoginInfo()
			.get(StorageLoginInfoEnum.skey.getKey())));
	try {
		HttpEntity entity = core.getMyHttpClient().doGet(url, params,
				false, null);
		String text = EntityUtils.toString(entity, Consts.UTF_8); // 无消息
		return true;
	} catch (Exception e) {
		LOG.debug(e.getMessage());
	}
	return false;
}
 
Example #3
Source File: RestDataBindingTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testForm() throws IOException {
    Assert.assertEquals("form", restService.bindForm("form"));

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost("http://127.0.0.1:8803/rest/bindForm");

    List<NameValuePair> list = new ArrayList<NameValuePair>();
    list.add(new BasicNameValuePair("formP", "formBBB"));
    HttpEntity httpEntity = new UrlEncodedFormEntity(list, Consts.UTF_8);

    httpPost.setEntity(httpEntity);

    HttpResponse httpResponse = httpclient.execute(httpPost);
    String result = EntityUtils.toString(httpResponse.getEntity());

    Assert.assertEquals("formBBB", result);
}
 
Example #4
Source File: MessageTools.java    From xiaoV with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 消息发送
 *
 * @param msgType
 * @param content
 * @param toUserName
 * @author https://github.com/yaphone
 * @date 2017年4月23日 下午2:32:02
 */
public static void webWxSendMsg(int msgType, String content,
		String toUserName) {
	String url = String.format(URLEnum.WEB_WX_SEND_MSG.getUrl(), core
			.getLoginInfo().get("url"));
	Map<String, Object> msgMap = new HashMap<String, Object>();
	msgMap.put("Type", msgType);
	msgMap.put("Content", content);
	msgMap.put("FromUserName", core.getUserName());
	msgMap.put("ToUserName", toUserName == null ? core.getUserName()
			: toUserName);
	msgMap.put("LocalID", new Date().getTime() * 10);
	msgMap.put("ClientMsgId", new Date().getTime() * 10);
	Map<String, Object> paramMap = core.getParamMap();
	paramMap.put("Msg", msgMap);
	paramMap.put("Scene", 0);
	try {
		String paramStr = JSON.toJSONString(paramMap);
		HttpEntity entity = myHttpClient.doPost(url, paramStr);
		EntityUtils.toString(entity, Consts.UTF_8);
	} catch (Exception e) {
		LOG.error("webWxSendMsg", e);
	}
}
 
Example #5
Source File: HttpProxyUtils.java    From android-uiconductor with Apache License 2.0 6 votes vote down vote up
public static String postRequestAsString(String url, String request)
    throws UicdDeviceHttpConnectionResetException {
  logger.info("post request to xmldumper:" + url);
  String ret = "";
  Response response = null;
  try {
    response = Request.Post(url)
        .body(new StringEntity(request))
        .execute();
    ret = response.returnContent().asString(Consts.UTF_8);
  } catch (IOException e) {
    logger.severe(e.getMessage());
    // See comments in getRequestAsString
    if (CONNECTION_RESET_KEYWORDS_LIST.stream().parallel().anyMatch(e.getMessage()::contains)) {
      throw new UicdDeviceHttpConnectionResetException(e.getMessage());
    }
  }
  logger.info("return from xmldumper:" + ret);
  return ret;
}
 
Example #6
Source File: QANARY.java    From chatbot with Apache License 2.0 6 votes vote down vote up
private String makeRequest(String question) {
        try {
            HttpPost httpPost = new HttpPost(URL);
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("query", question));
//            params.add(new BasicNameValuePair("lang", "it"));
            params.add(new BasicNameValuePair("kb", "dbpedia"));

            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, Consts.UTF_8);
            httpPost.setEntity(entity);

            HttpResponse response = client.execute(httpPost);

            // Error Scenario
            if(response.getStatusLine().getStatusCode() >= 400) {
                logger.error("QANARY Server could not answer due to: " + response.getStatusLine());
                return null;
            }

            return EntityUtils.toString(response.getEntity());
        }
        catch(Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }
 
Example #7
Source File: LoginServiceImpl.java    From xiaoV with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void wxStatusNotify() {
	// 组装请求URL和参数
	String url = String.format(URLEnum.STATUS_NOTIFY_URL.getUrl(), core
			.getLoginInfo().get(StorageLoginInfoEnum.pass_ticket.getKey()));

	Map<String, Object> paramMap = core.getParamMap();
	paramMap.put(StatusNotifyParaEnum.CODE.para(),
			StatusNotifyParaEnum.CODE.value());
	paramMap.put(StatusNotifyParaEnum.FROM_USERNAME.para(),
			core.getUserName());
	paramMap.put(StatusNotifyParaEnum.TO_USERNAME.para(),
			core.getUserName());
	paramMap.put(StatusNotifyParaEnum.CLIENT_MSG_ID.para(),
			System.currentTimeMillis());
	String paramStr = JSON.toJSONString(paramMap);

	try {
		HttpEntity entity = httpClient.doPost(url, paramStr);
		EntityUtils.toString(entity, Consts.UTF_8);
	} catch (Exception e) {
		LOG.error("微信状态通知接口失败!", e);
	}

}
 
Example #8
Source File: ClassTest.java    From clouddisk with MIT License 6 votes vote down vote up
public static void main(String args[]){
    HttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://localhost:8080/sso-web/upload");
    httpPost.addHeader("Range","bytes=10000-");
    final MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
    multipartEntity.setCharset(Consts.UTF_8);
    multipartEntity.setMode(HttpMultipartMode.STRICT);
    multipartEntity.addBinaryBody("file", new File("/Users/huanghuanlai/Desktop/test.java"));
    httpPost.setEntity(multipartEntity.build());
    try {
        HttpResponse response = httpClient.execute(httpPost);

    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #9
Source File: ApiRequestService.java    From ticket with GNU General Public License v3.0 6 votes vote down vote up
public boolean checkRandCodeAnsyn(String position, String token) {
    HttpUtil httpUtil = new HttpUtil();
    HttpPost httpPost = new HttpPost(apiConfig.getCheckRandCodeAnsyn());
    List<NameValuePair> formparams = new ArrayList<>();
    formparams.add(new BasicNameValuePair("randCode", position));
    formparams.add(new BasicNameValuePair("REPEAT_SUBMIT_TOKEN", token));
    formparams.add(new BasicNameValuePair("rand", "randp"));
    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
            Consts.UTF_8);
    httpPost.setEntity(urlEncodedFormEntity);
    String response = httpUtil.post(httpPost);

    Gson jsonResult = new Gson();
    Map rsmap = jsonResult.fromJson(response, Map.class);
    if (rsmap.getOrDefault("status", "").toString().equals("true")) {
        return true;
    }
    log.error("验证码错误", rsmap.get("result_message"));
    return false;
}
 
Example #10
Source File: HttpRestWb.java    From document-management-software with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static void createFolderSimpleJSON(CloseableHttpClient httpclient)
			throws UnsupportedEncodingException, IOException {

//		CloseableHttpClient httpclient = HttpClients.createDefault();

		// This will create a tree starting from the Default workspace
		String folderPath = "/Default/USA/NJ/Fair Lawn/createSimple/JSON";
		String input = "{ \"folderPath\" : \"" + folderPath + "\" }";
		System.out.println(input);

		HttpPost httppost = new HttpPost(BASE_PATH + "/services/rest/folder/createSimpleJSON");
		StringEntity entity = new StringEntity(input, ContentType.create("application/json", Consts.UTF_8));
		httppost.setEntity(entity);

		CloseableHttpResponse response = httpclient.execute(httppost);
		try {
			HttpEntity rent = response.getEntity();
			if (rent != null) {
				String respoBody = EntityUtils.toString(rent, "UTF-8");
				System.out.println(respoBody);
			}
		} finally {
			response.close();
		}
	}
 
Example #11
Source File: HTTPUtil.java    From simple-sso with Apache License 2.0 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 #12
Source File: ApiRequestService.java    From ticket with GNU General Public License v3.0 6 votes vote down vote up
public String uamtk(String userName) {
    HttpUtil httpUtil = UserTicketStore.httpUtilStore.get(userName);
    HttpPost httpPost = new HttpPost(apiConfig.getUamtk());
    List<NameValuePair> formparams = new ArrayList<>();
    formparams.add(new BasicNameValuePair("appid", "otn"));
    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
            Consts.UTF_8);
    httpPost.setEntity(urlEncodedFormEntity);
    Gson jsonResult = new Gson();
    String response = httpUtil.post(httpPost);
    Map rsmap = jsonResult.fromJson(response, Map.class);
    if ("0.0".equals(rsmap.getOrDefault("result_code", "").toString())) {
        UserTicketStore.httpUtilStore.put(userName, httpUtil);
        return rsmap.get("newapptk").toString();
    }
    return null;
}
 
Example #13
Source File: CouchDB.java    From julongchain with Apache License 2.0 6 votes vote down vote up
/**
 * WarmIndex method provides a function for warming a single index
 * @param designdoc
 * @param indexname
 * @return
 */
public Boolean warmIndex(CouchDbClient db, String designdoc,String indexname){
    Boolean boolFalg = false;
    try {
        List<NameValuePair> params = Lists.newArrayList();
        params.add(new BasicNameValuePair("stale", "update_after"));
        String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));

        String str = String.format("_design/%s/_view/%s?" + paramStr, designdoc, indexname);
        URI build = URIBuilderUtil.buildUri(db.getDBUri()).path(str).build();
        HttpGet get = new HttpGet(build);
        HttpResponse response = db.executeRequest(get);
        int code = response.getStatusLine().getStatusCode();
        if (code == 200){
            boolFalg = true;
        }
    } catch (Exception e) {
        boolFalg = false;
        e.printStackTrace();
    }
    return boolFalg;
}
 
Example #14
Source File: ApiRequestService.java    From ticket with GNU General Public License v3.0 6 votes vote down vote up
public boolean isLogin(UserModel userModel) {
    HttpUtil httpUtil = UserTicketStore.httpUtilStore.get(userModel.getUsername());
    HttpPost httpPost = new HttpPost(apiConfig.getUamtkStatic());
    List<NameValuePair> formparams = new ArrayList<>();
    formparams.add(new BasicNameValuePair("appid", "otn"));
    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
            Consts.UTF_8);
    httpPost.setEntity(urlEncodedFormEntity);
    String response = httpUtil.post(httpPost);
    Gson jsonResult = new Gson();
    Map rsmap = jsonResult.fromJson(response, Map.class);
    if ("0.0".equals(rsmap.get("result_code").toString())) {
        userModel.setUamtk(rsmap.get("newapptk").toString());
        UserTicketStore.httpUtilStore.put(userModel.getUsername(), httpUtil);
        return true;
    } else {
        return false;
    }
}
 
Example #15
Source File: HttpClientUtil.java    From DataLink with Apache License 2.0 6 votes vote down vote up
public String executeAndGet(HttpRequestBase httpRequestBase) throws Exception {
    HttpResponse response;
    String entiStr = "";
    try {
        response = httpClient.execute(httpRequestBase);

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            System.err.println("请求地址:" + httpRequestBase.getURI() + ", 请求方法:" + httpRequestBase.getMethod()
                    + ",STATUS CODE = " + response.getStatusLine().getStatusCode());

            throw new Exception("Response Status Code : " + response.getStatusLine().getStatusCode());
        } else {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                entiStr = EntityUtils.toString(entity, Consts.UTF_8);
            } else {
                throw new Exception("Response Entity Is Null");
            }
        }
    } catch (Exception e) {
        throw e;
    }

    return entiStr;
}
 
Example #16
Source File: FileUploadParser.java    From clouddisk with MIT License 6 votes vote down vote up
public HttpPost initRequest(final FileUploadParameter parameter) {
	final FileUploadAddress fileUploadAddress = getDependResult(FileUploadAddress.class);
	final HttpPost request = new HttpPost("http://" + fileUploadAddress.getData().getUp() + CONST.URI_PATH);
	final MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
	multipartEntity.setCharset(Consts.UTF_8);
	multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
	multipartEntity.addPart(CONST.QID_NAME, new StringBody(getLoginInfo().getQid(), ContentType.DEFAULT_BINARY));
	multipartEntity.addPart("ofmt", new StringBody("json", ContentType.DEFAULT_BINARY));
	multipartEntity.addPart("method", new StringBody("Upload.web", ContentType.DEFAULT_BINARY));
	multipartEntity.addPart("token", new StringBody(readCookieStoreValue("token"), ContentType.DEFAULT_BINARY));
	multipartEntity.addPart("v", new StringBody("1.0.1", ContentType.DEFAULT_BINARY));
	multipartEntity.addPart("tk", new StringBody(fileUploadAddress.getData().getTk(), ContentType.DEFAULT_BINARY));
	multipartEntity.addPart("Upload", new StringBody("Submit Query", ContentType.DEFAULT_BINARY));
	multipartEntity.addPart("devtype", new StringBody("web", ContentType.DEFAULT_BINARY));
	multipartEntity.addPart("pid", new StringBody("ajax", ContentType.DEFAULT_BINARY));
	multipartEntity.addPart("Filename",
			new StringBody(parameter.getUploadFile().getName(), ContentType.APPLICATION_JSON));
	multipartEntity.addPart("path", new StringBody(parameter.getPath(), ContentType.APPLICATION_JSON));// 解决中文不识别问题
	multipartEntity.addBinaryBody("file", parameter.getUploadFile());
	request.setEntity(multipartEntity.build());
	return request;
}
 
Example #17
Source File: HttpUtil.java    From database-transform-tool with Apache License 2.0 5 votes vote down vote up
/**
 * @decription URL编码
 * @author yi.zhang
 * @time 2017年9月15日 下午3:33:38
 * @param target
 * @return
 */
public static String encode(String target){
	String result = target;
	try {
		result = URLEncoder.encode(target, Consts.UTF_8.name());
	} catch (UnsupportedEncodingException e) {
		logger.error("--http encode error !",e);
	}
	return result;
}
 
Example #18
Source File: Gen_HTTP_QA_Sys.java    From NLIWOD with GNU Affero General Public License v3.0 5 votes vote down vote up
public HttpResponse fetchPostResponse(String url, Map<String, String> paramMap) throws ClientProtocolException, IOException {
	HttpResponse response = null;
	RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(this.timeout).build();
	HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
	HttpPost httppost = new HttpPost(url);

	List<NameValuePair> params = new ArrayList<>();
	for (String key : paramMap.keySet()) {
		params.add(new BasicNameValuePair(key, paramMap.get(key)));
	}
	UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, Consts.UTF_8);
	httppost.setEntity(entity);
	response = client.execute(httppost);
	return response;
}
 
Example #19
Source File: CreatePage.java    From bobcat with Apache License 2.0 5 votes vote down vote up
@Override
@Step("Create test page {data.contentPath}")
public void execute(SlingPageData data) throws AemPageManipulationException {
  HttpPost request = new HttpPost(authorIP + data.getContentPath());
  request.setEntity(new UrlEncodedFormEntity(data.getContent(), Consts.UTF_8));
  try {
    httpClient.execute(request);
  } catch (IOException e) {
    throw new AemPageManipulationException(e);
  } finally {
    request.releaseConnection();
  }
}
 
Example #20
Source File: DeletePage.java    From bobcat with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(SlingPageData data) throws AemPageManipulationException {
  HttpPost request = new HttpPost(authorIP + data.getContentPath());
  request.setEntity(new UrlEncodedFormEntity(
      Collections.singleton(new BasicNameValuePair(":operation", "delete")), Consts.UTF_8));
  try {
    httpClient.execute(request);
  } catch (IOException e) {
    throw new AemPageManipulationException(e);
  } finally {
    request.releaseConnection();
  }
}
 
Example #21
Source File: O365Token.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
public O365Token(String tenantId, String clientId, String redirectUri, String code) throws IOException {
    this.clientId = clientId;
    this.redirectUri = redirectUri;
    this.tokenUrl = "https://login.microsoftonline.com/"+tenantId+"/oauth2/token";

    ArrayList<NameValuePair> parameters = new ArrayList<>();
    parameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
    parameters.add(new BasicNameValuePair("code", code));
    parameters.add(new BasicNameValuePair("redirect_uri", redirectUri));
    parameters.add(new BasicNameValuePair("client_id", clientId));

    RestRequest tokenRequest = new RestRequest(tokenUrl, new UrlEncodedFormEntity(parameters, Consts.UTF_8));

    executeRequest(tokenRequest);
}
 
Example #22
Source File: LoginParser.java    From clouddisk with MIT License 5 votes vote down vote up
@Override
public HttpPost initRequest(final LoginParameter parameter) {
	final HttpPost request = new HttpPost(CONST.URI_PATH);
	final List<NameValuePair> data = new ArrayList<>();
	data.add(new BasicNameValuePair(CONST.SRC_KEY, CONST.SRC_VAL));
	data.add(new BasicNameValuePair(CONST.FROM_KEY, CONST.FROM_VAL));
	data.add(new BasicNameValuePair(CONST.CHARSET_KEY, CONST.SRC_VAL));
	data.add(new BasicNameValuePair(CONST.REQUESTSCEMA_KEY, CONST.REQUESTSCEMA_VAL));
	data.add(new BasicNameValuePair(CONST.O_KEY, CONST.O_VAL));
	data.add(new BasicNameValuePair(CONST.M_KEY, CONST.M_VAL));
	data.add(new BasicNameValuePair(CONST.LM_KEY, CONST.LM_VAL));
	data.add(new BasicNameValuePair(CONST.CAPTFLAG_KEY, CONST.CAPTFLAG_VAL));
	data.add(new BasicNameValuePair(CONST.RTYPE_KEY, CONST.RTYPE_VAL));
	data.add(new BasicNameValuePair(CONST.VALIDATELM_KEY, CONST.VALIDATELM_VAL));
	data.add(new BasicNameValuePair(CONST.ISKEEPALIVE_KEY, CONST.ISKEEPALIVE_VAL));
	data.add(new BasicNameValuePair(CONST.CAPTCHAAPP_KEY, CONST.CAPTCHAAPP_VAL));
	data.add(new BasicNameValuePair(CONST.USERNAME_NAME, loginUserToken.getAccount()));
	data.add(new BasicNameValuePair(CONST.TYPE_KEY, LoginConst.TYPE_VAL));
	data.add(new BasicNameValuePair(CONST.ACCOUNT_NAME, loginUserToken.getAccount()));
       data.add(new BasicNameValuePair(CONST.PASSWORD_NAME, loginUserToken.getPassword()));
	if (StringUtils.isNotBlank(parameter.getCaptchaValue())) {
		data.add(new BasicNameValuePair(CONST.CAPTCHA_KEY, parameter.getCaptchaValue()));
	} else {
		data.add(new BasicNameValuePair(CONST.CAPTCHA_KEY, StringUtils.EMPTY));
	}
	if (StringUtils.isNotBlank(parameter.getToken())) {
		data.add(new BasicNameValuePair(CONST.TOKEN_NAME, parameter.getToken()));
	} else {
		throw new CloudDiskException("登录所需token令牌不能为空.");
	}
	data.add(new BasicNameValuePair(LoginConst.PROXY_KEY, LoginConst.PROXY_VAL));

	request.setEntity(new UrlEncodedFormEntity(data, Consts.UTF_8));

	return request;
}
 
Example #23
Source File: FileSearchParser.java    From clouddisk with MIT License 5 votes vote down vote up
@Override
public HttpPost initRequest(final FileSearchParameter parameter) {
	final HttpPost request = new HttpPost(getRequestUri());
	final List<NameValuePair> data = new ArrayList<>(5);
	data.add(new BasicNameValuePair(CONST.KEY_NAME, parameter.getKey()));
	data.add(new BasicNameValuePair(CONST.ISFPATH_NAME, "1"));
	data.add(new BasicNameValuePair(CONST.PAGE_NAME, String.valueOf(parameter.getPage())));
	data.add(new BasicNameValuePair(CONST.PAGE_SIZE_NAME, String.valueOf(parameter.getPage_size())));
	data.add(new BasicNameValuePair(CONST.AJAX_KEY, CONST.AJAX_VAL));
	request.setEntity(new UrlEncodedFormEntity(data, Consts.UTF_8));
	return request;
}
 
Example #24
Source File: SentinelApiClient.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
/**
 * Build an `HttpUriRequest` in POST way.
 * 
 * @param url
 * @param params
 * @param supportEnhancedContentType see {@link #isSupportEnhancedContentType(String, String, int)}
 * @return
 */
protected static HttpUriRequest postRequest(String url, Map<String, String> params, boolean supportEnhancedContentType) {
    HttpPost httpPost = new HttpPost(url);
    if (params != null && params.size() > 0) {
        List<NameValuePair> list = new ArrayList<>(params.size());
        for (Entry<String, String> entry : params.entrySet()) {
            list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(list, Consts.UTF_8));
        if (!supportEnhancedContentType) {
            httpPost.setHeader(HTTP_HEADER_CONTENT_TYPE, HTTP_HEADER_CONTENT_TYPE_URLENCODED);
        }
    }
    return httpPost;
}
 
Example #25
Source File: HttpUtil.java    From database-transform-tool with Apache License 2.0 5 votes vote down vote up
/**
 * @decription URL解码
 * @author yi.zhang
 * @time 2017年9月15日 下午3:33:38
 * @param target
 * @return
 */
public static String decode(String target){
	String result = target;
	try {
		result = URLDecoder.decode(target, Consts.UTF_8.name());
	} catch (UnsupportedEncodingException e) {
		logger.error("--http decode error !",e);
	}
	return result;
}
 
Example #26
Source File: URIUtil.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Convert byte array to a UTF-8 string value.
 * @param bytes byte array
 * @return ASCII string
 */
public static String getString(final byte[] bytes) {
    if (bytes == null) {
        throw new IllegalArgumentException("Parameter may not be null");
    }

    return new String(bytes, Consts.UTF_8);
}
 
Example #27
Source File: HttpGetPostRequestMokUtil.java    From JavaWeb with Apache License 2.0 5 votes vote down vote up
public static HttpResponse httpClientForPost(String url,List<NameValuePair> list,HttpClient httpClient) throws Exception {
HttpPost post = new HttpPost(url);
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list,Consts.UTF_8);
post.setEntity(urlEncodedFormEntity);
HttpResponse httpResponse = httpClient.execute(post);
return httpResponse;
  }
 
Example #28
Source File: HttpRestWb.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void createFolderSimpleForm(CloseableHttpClient httpclient) throws Exception { 
	
	// This will create a tree starting from the Root folder (not in the Default workspace)
	List<NameValuePair> formparams = new ArrayList<NameValuePair>();
	formparams.add(new BasicNameValuePair("folderPath", "/LogicalDOC/USA/NJ/Fair Lawn/createSimple"));
	
	UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
	
	HttpPost httppost = new HttpPost(BASE_PATH + "/services/rest/folder/createSimpleForm");
	httppost.setEntity(entity);		

	CloseableHttpResponse response = httpclient.execute(httppost);
	int code = response.getStatusLine().getStatusCode();
	System.out.println("HTTPstatus code: "+ code);
	if (code == HttpStatus.SC_OK) {
	} else {
		//log.warn("status code is invalid: {}", code);
		System.err.println("status code is invalid: "+ code);
		throw new Exception(response.getStatusLine().getReasonPhrase());
	}				
	
	try {
		HttpEntity rent = response.getEntity();
		if (rent != null) {
			String respoBody = EntityUtils.toString(rent, "UTF-8");
			System.out.println(respoBody);
		}
	} finally {
		response.close();
	}
}
 
Example #29
Source File: FileExistParser.java    From clouddisk with MIT License 5 votes vote down vote up
@Override
public HttpPost initRequest(final FileExistParameter parameter) {
	final HttpPost request = new HttpPost(getRequestUri());
	final List<NameValuePair> data = new ArrayList<>(0);
	data.add(new BasicNameValuePair(CONST.DIR_NAME, parameter.getDir()));
	data.addAll(parameter.getFnames().stream().map(fame -> new BasicNameValuePair(CONST.FNAME_NAME, fame)).collect(Collectors.toList()));
	data.add(new BasicNameValuePair(CONST.AJAX_KEY, CONST.AJAX_VAL));
	request.setEntity(new UrlEncodedFormEntity(data, Consts.UTF_8));
	return request;
}
 
Example #30
Source File: StringResponseDecoder.java    From Bastion with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Bindings decode(Response response, DecodingHints hints) {
    try {
        Charset responseCharset = response.getContentType().map(ContentType::getCharset).orElse(Consts.ISO_8859_1);
        return Bindings.hierarchy(String.class, CharStreams.toString(new InputStreamReader(response.getBody(), responseCharset)));
    } catch (IOException ignored) {
        return new Bindings();
    }
}