org.apache.http.ParseException Java Examples

The following examples show how to use org.apache.http.ParseException. 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: ApacheGatewayConnectionTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
private void addMockedHeader(
        final HttpResponse httpResponseMock,
        final String name,
        final String value,
        HeaderElement[] elements) {
    final Header header = new Header() {
        @Override
        public String getName() {
            return name;
        }
        @Override
        public String getValue() {
            return value;
        }
        @Override
        public HeaderElement[] getElements() throws ParseException {
            return elements;
        }
    };
    when(httpResponseMock.getFirstHeader(name)).thenReturn(header);
}
 
Example #2
Source File: GNPSUtils.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Open website with GNPS job
 * 
 * @param resEntity
 */
private static void openWebsite(HttpEntity resEntity) {
  if (Desktop.isDesktopSupported()) {
    try {
      JSONObject res = new JSONObject(EntityUtils.toString(resEntity));
      String url = res.getString("url");
      logger.info("Response: " + res.toString());

      if (url != null && !url.isEmpty())
        Desktop.getDesktop().browse(new URI(url));

    } catch (ParseException | IOException | URISyntaxException | JSONException e) {
      logger.log(Level.SEVERE, "Error while submitting GNPS job", e);
    }
  }
}
 
Example #3
Source File: SKFSClient.java    From fido2 with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static String getAndVerifySuccessfulResponse(HttpResponse skfsResponse){
    try {
        String responseJsonString = EntityUtils.toString(skfsResponse.getEntity());
        Common.parseJsonFromString(responseJsonString);     //Response is valid JSON by parsing it

        if (skfsResponse.getStatusLine().getStatusCode() != 200
                || responseJsonString == null) {
            POCLogger.logp(Level.SEVERE, CLASSNAME, "verifySuccessfulCall",
                    "POC-ERR-5001", skfsResponse);
            throw new WebServiceException(POCLogger.getMessageProperty("POC-ERR-5001"));
        }

        return responseJsonString;
    } catch (IOException | ParseException ex) {
        POCLogger.logp(Level.SEVERE, CLASSNAME, "verifySuccessfulCall",
                "POC-ERR-5001", ex.getLocalizedMessage());
        throw new WebServiceException(POCLogger.getMessageProperty("POC-ERR-5001"));
    }
}
 
Example #4
Source File: RequestAsync.java    From Almost-Famous with MIT License 6 votes vote down vote up
protected String getHttpContent(HttpResponse response) {

        HttpEntity entity = response.getEntity();
        String body = null;

        if (entity == null) {
            return null;
        }

        try {
            body = EntityUtils.toString(entity, "utf-8");
        } catch (ParseException | IOException e) {
            LOG.error("the response's content input stream is corrupt", e);
        }
        return body;
    }
 
Example #5
Source File: RequestSync.java    From Almost-Famous with MIT License 6 votes vote down vote up
protected String getHttpContent(HttpResponse response) {

        HttpEntity entity = response.getEntity();
        String body = null;

        if (entity == null) {
            return null;
        }

        try {
            body = EntityUtils.toString(entity, "utf-8");
        } catch (ParseException | IOException e) {
            LOG.error("the response's content input stream is corrupt", e);
        }
        return body;
    }
 
Example #6
Source File: PacHttpUtils.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param rest
 *            URL for POST method
 * @return String
 * @throws Exception
 */
public static String doHttpPost(final String url, final String requestBody) throws Exception {
	try {

		HttpClient client = HttpClientBuilder.create().build();
		HttpPost httppost = new HttpPost(url);
		httppost.setHeader(CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
		StringEntity jsonEntity = new StringEntity(requestBody);
		httppost.setEntity(jsonEntity);
		HttpResponse httpresponse = client.execute(httppost);
		int statusCode = httpresponse.getStatusLine().getStatusCode();
		if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
			return EntityUtils.toString(httpresponse.getEntity());
		} else {
			LOGGER.error("URL: " + url + " Body: " + requestBody);
			throw new Exception(
					"unable to execute post request to " + url + " because " + httpresponse.getStatusLine().getReasonPhrase());
		}
	} catch (ParseException parseException) {
		LOGGER.error("error closing issue" + parseException);
		throw parseException;
	} catch (Exception exception) {
		LOGGER.error("error closing issue" + exception.getMessage());
		throw exception;
	}
}
 
Example #7
Source File: PacHttpUtils.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param url for PUT method
 * @param requestBody for PUT method
 * @return String
 * @throws Exception
 */
public static String doHttpPut(final String url, final String requestBody) throws Exception {
	try {

		HttpClient client = HttpClientBuilder.create().build();
		HttpPut httpput = new HttpPut(url);
		httpput.setHeader(CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
		StringEntity jsonEntity = new StringEntity(requestBody);
		httpput.setEntity(jsonEntity);
		HttpResponse httpresponse = client.execute(httpput);
		int statusCode = httpresponse.getStatusLine().getStatusCode();
		if (statusCode == HttpStatus.SC_OK) {
			return EntityUtils.toString(httpresponse.getEntity());
		} else {
			LOGGER.error(requestBody);
			throw new Exception("unable to execute post request because " + httpresponse.getStatusLine().getReasonPhrase());
		}
	} catch (ParseException parseException) {
		LOGGER.error("error closing issue" + parseException);
		throw parseException;
	} catch (Exception exception) {
		LOGGER.error("error closing issue" + exception.getMessage());
		throw exception;
	}
}
 
Example #8
Source File: PacHttpUtils.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param rest
 *            URL for POST method
 * @return String
 * @throws Exception
 */
public static String doHttpPost(final String url, final String requestBody) throws Exception {
	try {

		HttpClient client = HttpClientBuilder.create().build();
		HttpPost httppost = new HttpPost(url);
		httppost.setHeader(CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
		StringEntity jsonEntity = new StringEntity(requestBody);
		httppost.setEntity(jsonEntity);
		HttpResponse httpresponse = client.execute(httppost);
		int statusCode = httpresponse.getStatusLine().getStatusCode();
		if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
			return EntityUtils.toString(httpresponse.getEntity());
		} else {
			LOGGER.error(requestBody);
			throw new Exception(
					"unable to execute post request because " + httpresponse.getStatusLine().getReasonPhrase());
		}
	} catch (ParseException parseException) {
		LOGGER.error("error closing issue" + parseException);
		throw parseException;
	} catch (Exception exception) {
		LOGGER.error("error closing issue" + exception.getMessage());
		throw exception;
	}
}
 
Example #9
Source File: ESManager.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch data and scroll id.
 *
 * @param endPoint
 *            the end point
 * @param _data
 *            the data
 * @param keyField
 *            the key field
 * @param payLoad
 *            the pay load
 * @return the string
 */
private static String fetchDataAndScrollId(String endPoint, List<Map<String, String>> _data, String payLoad) {
    try {
        ObjectMapper objMapper = new ObjectMapper();
        Response response = invokeAPI("GET", endPoint, payLoad);
        String responseJson = EntityUtils.toString(response.getEntity());
        JsonNode _info = objMapper.readTree(responseJson).at("/hits/hits");
        String scrollId = objMapper.readTree(responseJson).at("/_scroll_id").textValue();
        Iterator<JsonNode> it = _info.elements();
        String doc;
        Map<String, String> docMap;
        while (it.hasNext()) {
            doc = it.next().fields().next().getValue().toString();
            docMap = objMapper.readValue(doc, new TypeReference<Map<String, String>>() {
            });
            docMap.remove("discoverydate");
            docMap.remove("_loaddate");
            docMap.remove("id");
            _data.add(docMap);
        }
        return scrollId;
    } catch (ParseException | IOException e) {
        LOGGER.error("Error in fetchDataAndScrollId" ,e );
    }
    return "";
}
 
Example #10
Source File: ESManager.java    From pacbot with Apache License 2.0 6 votes vote down vote up
private static String fetchDataAndScrollId(String endPoint, Map<String, Map<String, String>> _data, String payLoad) {
    try {
        ObjectMapper objMapper = new ObjectMapper();
        Response response = invokeAPI("GET", endPoint, payLoad);
        String responseJson = EntityUtils.toString(response.getEntity());
        JsonNode _info = objMapper.readTree(responseJson).at("/hits/hits");
        String scrollId = objMapper.readTree(responseJson).at("/_scroll_id").textValue();
        Iterator<JsonNode> it = _info.elements();
        String doc;
        Map<String, String> docMap;
        while (it.hasNext()) {
            doc = it.next().fields().next().getValue().toString();
            docMap = objMapper.readValue(doc, new TypeReference<Map<String, String>>() {
            });
            _data.put(docMap.get("checkid")+"_"+docMap.get("accountid"), docMap);
        }
        return scrollId;
    } catch (ParseException | IOException e) {
        LOGGER.error("Error in fetchDataAndScrollId" ,e );
    }
    return "";
}
 
Example #11
Source File: ElasticSearchManager.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch data and scroll id.
 *
 * @param endPoint the end point
 * @param _data the data
 * @param keyField the key field
 * @param payLoad the pay load
 * @return the string
 */
private static String fetchDataAndScrollId(String endPoint, Map<String, Map<String, String>> _data, String keyField,
        String payLoad) {
    try {
        ObjectMapper objMapper = new ObjectMapper();
        Response response = invokeAPI("GET", endPoint, payLoad);
        String responseJson = EntityUtils.toString(response.getEntity());
        JsonNode _info = objMapper.readTree(responseJson).at("/hits/hits");
        String scrollId = objMapper.readTree(responseJson).at("/_scroll_id").textValue();
        Iterator<JsonNode> it = _info.elements();
        while (it.hasNext()) {
            String doc = it.next().fields().next().getValue().toString();
            Map<String, String> docMap = new ObjectMapper().readValue(doc,
                    new TypeReference<Map<String, String>>() {
                    });
            _data.put(docMap.get(keyField), docMap);
            docMap.remove(keyField);
        }
        return scrollId;
    } catch (ParseException | IOException e) {
        LOGGER.error("Error fetchDataAndScrollId ", e);
    }
    return "";

}
 
Example #12
Source File: PacmanUtils.java    From pacbot with Apache License 2.0 6 votes vote down vote up
private static Long calculateDuration(String date) throws java.text.ParseException {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    SimpleDateFormat dateFormat1 = new SimpleDateFormat("M/d/yyyy H:m");
    Date givenDate = null;
    String givenDateStr = null;
    try {
        givenDate = dateFormat.parse(date);
        givenDateStr = dateFormat1.format(givenDate);
    } catch (ParseException e) {
        logger.error("Parse exception occured : ", e);
        throw new RuleExecutionFailedExeption("Parse exception occured : " + e);
    }
    LocalDate givenLoacalDate = LocalDateTime.parse(givenDateStr, DateTimeFormatter.ofPattern("M/d/yyyy H:m"))
            .toLocalDate();
    LocalDate today = LocalDateTime.now().toLocalDate();
    return java.time.temporal.ChronoUnit.DAYS.between(givenLoacalDate, today);

}
 
Example #13
Source File: SKFSClient.java    From fido2 with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static String getAndVerifySuccessfulResponse(HttpResponse skfsResponse){
    try {
        String responseJsonString = EntityUtils.toString(skfsResponse.getEntity());
        verifyJson(responseJsonString);

        if (skfsResponse.getStatusLine().getStatusCode() != 200
                || responseJsonString == null) {
            WebauthnTutorialLogger.logp(Level.SEVERE, CLASSNAME, "verifySuccessfulCall",
                    "WEBAUTHN-ERR-5001", skfsResponse);
            throw new WebServiceException(WebauthnTutorialLogger.getMessageProperty("WEBAUTHN-ERR-5001"));
        }

        return responseJsonString;
    } catch (IOException | ParseException ex) {
        WebauthnTutorialLogger.logp(Level.SEVERE, CLASSNAME, "verifySuccessfulCall",
                "WEBAUTHN-ERR-5001", ex.getLocalizedMessage());
        throw new WebServiceException(WebauthnTutorialLogger.getMessageProperty("WEBAUTHN-ERR-5001"));
    }
}
 
Example #14
Source File: Remote.java    From HongsCORE with MIT License 6 votes vote down vote up
/**
 * 简单远程请求
 *
 * @param type
 * @param kind
 * @param url
 * @param data
 * @param head
 * @return
 * @throws HongsException
 * @throws StatusException
 * @throws SimpleException
 */
public static String request(METHOD type, FORMAT kind, String url, Map<String, Object> data, Map<String, String> head)
        throws HongsException, StatusException, SimpleException {
    final String         [ ] txt = new String         [1];
    final SimpleException[ ] err = new SimpleException[1];
    request(type, kind, url, data, head, (rsp) -> {
        try {
            txt[0] = EntityUtils.toString(rsp.getEntity(), "UTF-8").trim();
        } catch (IOException | ParseException ex) {
            err[0] = new SimpleException(url, ex);
        }
    });
    if (null != err[0]) {
        throw   err[0];
    }   return  txt[0];
}
 
Example #15
Source File: ApiClientResponseTest.java    From amex-api-java-client-core with Apache License 2.0 6 votes vote down vote up
@Test
public void valid() {
    Header[] headers = {new Header() {
        public String getName() {
            return "session_id";
        }

        public String getValue() {
            return "12345";
        }

        public HeaderElement[] getElements() throws ParseException {
            return new HeaderElement[0];
        }
    }};
    ApiClientResponse response = new ApiClientResponse(headers, "{\"key\":\"value\"}");

    assertEquals("12345", response.getHeader("session_id"));
    assertEquals("{\n  \"key\" : \"value\"\n}", response.toJson());
    assertEquals("value", response.getField("key"));
}
 
Example #16
Source File: AbstractWebUtils.java    From sanshanblog with Apache License 2.0 6 votes vote down vote up
/**
 * GET请求
 *
 * @param url          URL
 * @param parameterMap 请求参数
 * @return 返回结果
 */
public static String get(String url, Map<String, ?> parameterMap) {

    String result = null;
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        if (parameterMap != null) {
            parameterMap.forEach((k, v) -> {
                String value = String.valueOf(v);
                if (StringUtils.isNoneEmpty(value)) {
                    nameValuePairs.add(new BasicNameValuePair(k, value));
                }
            });
        }
        HttpGet httpGet = new HttpGet(url + (url.contains("?") ? "&" : "?") + EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")));
        CloseableHttpResponse httpResponse = HTTP_CLIENT.execute(httpGet);
        result = consumeResponse(httpResponse, "UTF-8");
    } catch (ParseException | IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    return result;
}
 
Example #17
Source File: AbstractWebUtils.java    From sanshanblog with Apache License 2.0 6 votes vote down vote up
/**
 * POST请求
 *
 * @param url          URL
 * @param parameterMap 请求参数
 * @param encoding 编码格式
 * @return 返回结果
 */
public static String post(String url, Map<String, ?> parameterMap, String encoding) {
    String result = null;
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        if (parameterMap != null) {
            parameterMap.forEach((k, v) -> {
                String value = String.valueOf(v);
                if (StringUtils.isNoneEmpty(value)) {
                    nameValuePairs.add(new BasicNameValuePair(k, value));
                }
            });
        }
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, encoding));
        CloseableHttpResponse httpResponse = HTTP_CLIENT.execute(httpPost);
        result = consumeResponse(httpResponse, encoding);
    } catch (ParseException | IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    return result;
}
 
Example #18
Source File: SysCrawlerRulerInfoService.java    From danyuan-application with Apache License 2.0 6 votes vote down vote up
/**
 * @throws IOException
 * @throws ParseException
 * @方法名 start
 * @功能 TODO(这里用一句话描述这个方法的作用)
 * @参数 @param list
 * @参数 @return
 * @返回 String
 * @author Administrator
 * @throws
 */
public String start(List<SysCrawlerRulerInfo> list) throws ParseException, IOException {
	for (SysCrawlerRulerInfo sysCrawlerRulerInfo : list) {
		if ("0".equals(sysCrawlerRulerInfo.getStatue())) {
			// 启动任务
			Map<String, String> map = new HashMap<>();
			map.put("uuid", sysCrawlerRulerInfo.getUuid());
			map.put("taskUuid", sysCrawlerRulerInfo.getUuid());
			map.put("contentInfo", sysCrawlerRulerInfo.getContentJsonInfo());
			map.put("delete", sysCrawlerRulerInfo.getDeleteFlag() + "");
			map.put("statue", "1");
			HttpUtil.postJson("http://127.0.0.1:3000/crawler", map, "UTF-8");
		}
		sysCrawlerRulerInfo.setStatue("1");
		sysCrawlerRulerInfoDao.save(sysCrawlerRulerInfo);
	}
	return "1";
}
 
Example #19
Source File: UnionService.java    From seezoon-framework-all with Apache License 2.0 6 votes vote down vote up
/**
 * https://upay.10010.com/npfweb/NpfWeb/buyCard/checkPhoneVerifyCode?callback=checkSuccess&commonBean.phoneNo=13249073372&phoneVerifyCode=932453&timeStamp=0.3671002044464746
 * @throws ParseException
 * @throws Exception
 * sendSuccess('true') 返回格式
 */
@Test
public void checkChargeSms() throws ParseException, Exception {
	String mobile = "13249073372";
	CookieStore cookieStore = valueOperations.get(mobile);
	HttpClientContext httpClientContext = HttpClientContext.create();
	httpClientContext.setCookieStore(cookieStore);
	MultiValueMap<String,String> params =  new LinkedMultiValueMap<>();
	params.put("commonBean.phoneNo", Lists.newArrayList(mobile));
	params.put("phoneVerifyCode", Lists.newArrayList("904114"));
	params.put("timeStamp", Lists.newArrayList(String.valueOf(System.currentTimeMillis())));

	String url = UriComponentsBuilder.fromHttpUrl("https://upay.10010.com/npfweb/NpfWeb/buyCard/checkPhoneVerifyCode").queryParams(params).build().toUriString();
	HttpGet request = new HttpGet(url);
	request.setHeader("Referer", "https://upay.10010.com/npfweb/npfbuycardweb/buycard_recharge_fill.htm");
	request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
	CloseableHttpResponse response = client.execute(request, httpClientContext);
	System.out.println("response:" + JSON.toJSONString(response));
	if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {// 成功
		HttpEntity entity = response.getEntity();
		if (null != entity) {
			String result = EntityUtils.toString(entity, "UTF-8");
			EntityUtils.consume(entity);
			System.out.println("result" + result);
		} else {
			throw new ServiceException("请求无数据返回");
		}
	} else {
		throw new ServiceException("请求状态异常失败");
	}
}
 
Example #20
Source File: Checks.java    From gerrit-code-review-plugin with Apache License 2.0 6 votes vote down vote up
private CheckInfo performCreateOrUpdate(CheckInput input)
    throws RestApiException, URISyntaxException, ParseException, IOException {
  HttpPost request = new HttpPost(buildRequestUrl());
  String inputString =
      JsonBodyParser.createRequestBody(input, new TypeToken<CheckInput>() {}.getType());
  request.setEntity(new StringEntity(inputString));
  request.setHeader("Content-type", "application/json");

  try (CloseableHttpResponse response = client.execute(request)) {
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
      return JsonBodyParser.parseResponse(
          EntityUtils.toString(response.getEntity()), new TypeToken<CheckInfo>() {}.getType());
    }
    throw new RestApiException(
        String.format("Request returned status %s", response.getStatusLine().getStatusCode()));
  }
}
 
Example #21
Source File: ESManager.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch data and scroll id.
 *
 * @param endPoint
 *            the end point
 * @param _data
 *            the data
 * @param keyField
 *            the key field
 * @param payLoad
 *            the pay load
 * @return the string
 */
private static String fetchDataAndScrollId(String endPoint, Map<String, Map<String, String>> _data, String keyField,
        String payLoad) {
    try {
        ObjectMapper objMapper = new ObjectMapper();
        Response response = invokeAPI("GET", endPoint, payLoad);
        String responseJson = EntityUtils.toString(response.getEntity());
        JsonNode _info = objMapper.readTree(responseJson).at("/hits/hits");
        String scrollId = objMapper.readTree(responseJson).at("/_scroll_id").textValue();
        Iterator<JsonNode> it = _info.elements();
        String doc;
        Map<String, String> docMap;
        while (it.hasNext()) {
            doc = it.next().fields().next().getValue().toString();
            docMap = objMapper.readValue(doc, new TypeReference<Map<String, String>>() {
            });
            _data.put(docMap.get(keyField), docMap);
            docMap.remove(keyField);
        }
        return scrollId;
    } catch (ParseException | IOException e) {
        LOGGER.error("Error in fetchDataAndScrollId" ,e );
    }
    return "";
}
 
Example #22
Source File: PacmanUtils.java    From pacbot with Apache License 2.0 6 votes vote down vote up
public static String doHttpGet(final String url, Map<String, String> headers) throws Exception {
    try {

        HttpClient client = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader(PacmanRuleConstants.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
        Set<Entry<String, String>> entrySet = headers.entrySet();
        for (Entry<String, String> entry : entrySet) {
            httpGet.setHeader(entry.getKey(), entry.getValue());
        }
        HttpResponse httpresponse = client.execute(httpGet);
        int statusCode = httpresponse.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
            return EntityUtils.toString(httpresponse.getEntity());
        } else {
            throw new Exception("unable to execute post request because "
                    + httpresponse.getStatusLine().getReasonPhrase());
        }
    } catch (ParseException parseException) {
        throw parseException;
    } catch (Exception exception) {
        throw exception;
    }
}
 
Example #23
Source File: HttpJsonDataUtils.java    From ais-sdk with Apache License 2.0 5 votes vote down vote up
public static String requestToString(HttpRequestBase httpReq) throws ParseException, IOException {
    final StringBuilder builder = new StringBuilder("\n")
            .append(httpReq.getMethod())
            .append(" ")
            .append(httpReq.getURI())
            .append(headersToString(httpReq.getAllHeaders()));
    if (httpReq instanceof HttpEntityEnclosingRequestBase) {
        builder.append("request body:").append(entityToPrettyString(((HttpEntityEnclosingRequestBase) httpReq)
                .getEntity()));
    }
    return builder.toString();
}
 
Example #24
Source File: UnionService.java    From seezoon-framework-all with Apache License 2.0 5 votes vote down vote up
/**
 * https://uac.10010.com/portal/Service/MallLogin?callback=jQuery17205929719702722311_1528559748927&
 * req_time=1528560369879&redirectURL=http%3A%2F%2Fwww.10010.com&userName=13249073372&
 * password=844505&pwdType=02&productType=01&redirectType=06&rememberMe=1&_=1528560369879
 * @throws Exception 
 * @throws ParseException 
 */
@Test
public void login() throws ParseException, Exception {
	HttpClientContext httpClientContext = HttpClientContext.create();
	String mobile = "13249073372";
	MultiValueMap<String,String> params =  new LinkedMultiValueMap<>();
	params.put("req_time", Lists.newArrayList(String.valueOf(System.currentTimeMillis())));
	params.put("_=", Lists.newArrayList(String.valueOf(System.currentTimeMillis())));
	params.put("redirectURL", Lists.newArrayList("http%3A%2F%2Fwww.10010.com"));
	params.put("userName", Lists.newArrayList(mobile));
	params.put("password", Lists.newArrayList("950102"));
	params.put("pwdType", Lists.newArrayList("02"));
	params.put("productType", Lists.newArrayList("01"));
	params.put("redirectType", Lists.newArrayList("06"));
	params.put("rememberMe", Lists.newArrayList("1"));

	String url = UriComponentsBuilder.fromHttpUrl("https://uac.10010.com/portal/Service/MallLogin").queryParams(params).build().toUriString();
	HttpGet request = new HttpGet(url);
	request.setHeader("Referer", "https://uac.10010.com/portal/custLogin");
	request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
	CloseableHttpResponse response = client.execute(request, httpClientContext);
	System.out.println("response:" + JSON.toJSONString(response));
	if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {// 成功
		HttpEntity entity = response.getEntity();
		if (null != entity) {
			String result = EntityUtils.toString(entity, "UTF-8");
			EntityUtils.consume(entity);
			System.out.println("result" + result);
		} else {
			throw new ServiceException("请求无数据返回");
		}
	} else {
		throw new ServiceException("请求状态异常失败");
	}
	CookieStore cookie = httpClientContext.getCookieStore();
	System.out.println("cookie:" + JSON.toJSONString(cookie));
	valueOperations.set(mobile, cookie, 60, TimeUnit.MINUTES);
}
 
Example #25
Source File: HttpClientResponse.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
public HttpClientResponse(CloseableHttpResponse response) throws ParseException, IOException {
    this.response = response;

    HttpEntity entity = response.getEntity();
    if (entity != null) {
        body = EntityUtils.toString(entity);
    }
}
 
Example #26
Source File: Report.java    From DiscordBot with Apache License 2.0 5 votes vote down vote up
@Override
public void action(String[] args, MessageReceivedEvent event) throws ParseException, IOException {

    List<Member> admins = new ArrayList<>();
    User traitor = event.getMessage().getMentionedUsers().get(0);
    Member author = event.getMember();

    StringBuilder argsString = new StringBuilder();
    Arrays.stream(args).forEach(s -> argsString.append(" " + s));
    String reason = argsString.toString().replace("@" + event.getGuild().getMember(traitor).getEffectiveName(), "").substring(2);

    event.getGuild().getMembers().stream()
            .filter(m -> Perms.getLvl(m) > 1)
            .forEach(m -> admins.add(m));

    StringBuilder sendTo = new StringBuilder();
    admins.forEach(m -> sendTo.append(", " + m.getUser().getAsMention()));

    admins.forEach(m -> m.getUser().openPrivateChannel().complete().sendMessage(
            new EmbedBuilder()
                    .setAuthor(m.getEffectiveName() + " submitted a report.", null, m.getUser().getAvatarUrl())
                    .addField("Author", author.getEffectiveName() + " (" + author.getAsMention() + ")", true)
                    .addField("Reported Member", traitor.getName() + " (" + traitor.getAsMention() + ")", true)
                    .addField("Reason", reason, false)
                    .build()
    ).queue());

    author.getUser().openPrivateChannel().complete().sendMessage(
            new EmbedBuilder()
                .setDescription("Thanks for your report submit.\nYour report got send by direct message to " + sendTo.toString() + ".")
                .build()
    ).queue();

}
 
Example #27
Source File: HttpUtil.java    From danyuan-application with Apache License 2.0 5 votes vote down vote up
public static String postJson(String url, Map<String, String> map, String encoding) throws ParseException, IOException {
	String body = "";

	// 创建httpclient对象
	CloseableHttpClient client = HttpClients.createDefault();
	// 创建post方式请求对象
	HttpPost httpPost = new HttpPost(url);

	// 装填参数
	httpPost.setEntity(new StringEntity(JSON.toJSONString(map), "UTF-8"));

	System.out.println("请求地址:" + url);
	System.out.println("请求参数:" + map.toString().toString());

	// 设置header信息
	// 指定报文头【Content-type】、【User-Agent】
	httpPost.setHeader("Content-type", "application/json");
	httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

	// 执行请求操作,并拿到结果(同步阻塞)
	CloseableHttpResponse response = client.execute(httpPost);
	// 获取结果实体
	HttpEntity entity = response.getEntity();
	if (entity != null) {
		// 按指定编码转换结果实体为String类型
		body = EntityUtils.toString(entity, encoding);
	}
	EntityUtils.consume(entity);
	// 释放链接
	response.close();
	System.out.println("响应数据:" + body);
	return body;
}
 
Example #28
Source File: HttpUtil.java    From danyuan-application with Apache License 2.0 5 votes vote down vote up
public static String post(String url, Map<String, String> map, String encoding) throws ParseException, IOException {
	String body = "";

	// 创建httpclient对象
	CloseableHttpClient client = HttpClients.createDefault();
	// 创建post方式请求对象
	HttpPost httpPost = new HttpPost(url);

	// 装填参数
	List<NameValuePair> nvps = new ArrayList<>();
	if (map != null) {
		for (Entry<String, String> entry : map.entrySet()) {
			nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
	}
	// 设置参数到请求对象中
	httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));

	System.out.println("请求地址:" + url);
	System.out.println("请求参数:" + nvps.toString());

	// 设置header信息
	// 指定报文头【Content-type】、【User-Agent】
	httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
	httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

	// 执行请求操作,并拿到结果(同步阻塞)
	CloseableHttpResponse response = client.execute(httpPost);
	// 获取结果实体
	HttpEntity entity = response.getEntity();
	if (entity != null) {
		// 按指定编码转换结果实体为String类型
		body = EntityUtils.toString(entity, encoding);
	}
	EntityUtils.consume(entity);
	// 释放链接
	response.close();
	System.out.println("响应数据:" + body);
	return body;
}
 
Example #29
Source File: FileStationService.java    From torrssen2 with MIT License 5 votes vote down vote up
public boolean delete(String path) {
    log.debug("File Station Delete");
    boolean ret = false;

    try {
        baseUrl = "http://" + settingService.getSettingValue("DS_HOST") + ":"
                + settingService.getSettingValue("DS_PORT") + "/webapi";

        URIBuilder builder = new URIBuilder(baseUrl + "/entry.cgi");
        builder.setParameter("api", "SYNO.FileStation.Delete").setParameter("version", "2")
                .setParameter("method", "start").setParameter("path", path).setParameter("recursive", "true")
                .setParameter("_sid", sid);

        JSONObject resJson = executeGet(builder);

        log.debug(builder.toString());

        if (resJson != null) {
            log.debug(resJson.toString());
            if (resJson.has("success")) {
                if (Boolean.parseBoolean(resJson.get("success").toString())) {
                    ret = true;
                }
            }
        }

    } catch (URISyntaxException | ParseException | JSONException e) {
        log.error(e.getMessage());
    }

    return ret;
}
 
Example #30
Source File: PacHttpUtils.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param rest
 *            URL for HTTP GET method
 * @param rest
 *            headers for HTTPS GET method
 * @return String
 * @throws IOException
 * @throws ParseException
 */
public static String getHttpGet(final String url, final Map<String, String> headers)
		throws ParseException, IOException {
	HttpClient client = HttpClientBuilder.create().build();
	HttpGet httpGet = new HttpGet(url);
	if (headers != null) {
		for (Map.Entry<String, String> entry : headers.entrySet()) {
			httpGet.setHeader(entry.getKey(), entry.getValue());
		}
	}
	HttpResponse httpresponse = client.execute(httpGet);
	return EntityUtils.toString(httpresponse.getEntity());
}