org.apache.http.HttpHeaders.CONTENT_TYPE

Here are the examples of the java api org.apache.http.HttpHeaders.CONTENT_TYPE taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

215 Examples 7

19 Source : AesClientTest.java
with Apache License 2.0
from youtongluan

// 加密传输的例子。展示了使用表单以及不使用表单两种方式
@Test
public void aes_base64() throws Exception {
    String charset = "UTF-8";
    HttpClient client = HttpClientBuilder.create().build();
    HttpResponse resp = login(client);
    String key_str = resp.getFirstHeader("skey").getValue();
    Log.get("login").info("key:{}", key_str);
    byte[] key = Base64.getMimeDecoder().decode(key_str);
    String act = "aes_base64";
    HttpPost post = new HttpPost(getUrl(act));
    Map<String, Object> json = new HashMap<>();
    json.put("echo", "你好!!!");
    json.put("names", Arrays.asList("小明", "小张"));
    byte[] conts = Encrypt.encrypt(S.json().toJson(json).getBytes(charset), key);
    String req = Base64.getEncoder().encodeToString(conts);
    System.out.println("req:" + req);
    post.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    StringEnreplacedy se = new StringEnreplacedy("data=" + URLEncoder.encode(req, "ASCII"), charset);
    post.setEnreplacedy(se);
    resp = client.execute(post);
    String line = resp.getStatusLine().toString();
    Log.get("aes_base64").info(line);
    replacedert.replacedertEquals("HTTP/1.1 200 OK", line);
    HttpEnreplacedy resEnreplacedy = resp.getEnreplacedy();
    String raw = EnreplacedyUtils.toString(resEnreplacedy);
    Log.get("aes").info("raw resp:{}", raw);
    byte[] contentBytes = Base64.getMimeDecoder().decode(raw);
    String ret = new String(Encrypt.decrypt(contentBytes, key), charset);
    Log.get("aes_base64").info("服务器返回:" + ret);
    replacedert.replacedertEquals("[\"你好!!! 小明\",\"你好!!! 小张\"]", ret);
    /*
		 * 非表单MIME的方式提交,去掉application/x-www-form-urlencoded,内容也不要URLEncoder编码
		 */
    post = new HttpPost(getUrl(act));
    System.out.println("req:" + req);
    se = new StringEnreplacedy("data=" + req, charset);
    post.setEnreplacedy(se);
    resp = client.execute(post);
    line = resp.getStatusLine().toString();
    Log.get("aes_base64").info(line);
    replacedert.replacedertEquals("HTTP/1.1 200 OK", line);
    resEnreplacedy = resp.getEnreplacedy();
    raw = EnreplacedyUtils.toString(resEnreplacedy);
    Log.get("aes").info("raw resp:{}", raw);
    contentBytes = Base64.getMimeDecoder().decode(raw);
    ret = new String(Encrypt.decrypt(contentBytes, key), charset);
    Log.get("aes_base64").info("服务器返回:" + ret);
    replacedert.replacedertEquals("[\"你好!!! 小明\",\"你好!!! 小张\"]", ret);
    post = new HttpPost(getUrl("bizError"));
    resp = client.execute(post);
    replacedert.replacedertEquals(550, resp.getStatusLine().getStatusCode());
    resEnreplacedy = resp.getEnreplacedy();
    String errMsg = EnreplacedyUtils.toString(resEnreplacedy);
    Log.get("aes").info("raw resp:{}", errMsg);
    replacedert.replacedertEquals("{\"code\":12345,\"message\":\"业务异常\"}", errMsg);
}

19 Source : ESBJAVA4469CallMediatorWithOutOnlyTestCase.java
with Apache License 2.0
from wso2

@Test(groups = { "wso2.esb" })
public void outOnlyWithoutContentAwareMediatorTest() throws Exception {
    WireMonitorServer wireMonitorServer = new WireMonitorServer(3828);
    Map<String, String> headers = new HashMap<>();
    wireMonitorServer.start();
    headers.put(HttpHeaders.CONTENT_TYPE, "text/xml");
    headers.put(HTTPConstants.HEADER_SOAP_ACTION, "urn:placeOrder");
    HttpResponse response = HttpRequestUtil.doPost(new URL(getProxyServiceURLHttp("ESBJAVA4469")), messageBody, headers);
    replacedert.replacedertEquals(response.getResponseCode(), HttpStatus.SC_ACCEPTED, "Response code should be 202");
    String outGoingMessage = wireMonitorServer.getCapturedMessage();
    replacedert.replacedertTrue(outGoingMessage.contains(">WSO2<"), "Outgoing message is empty or invalid content " + outGoingMessage);
}

19 Source : ESBJAVA4469CallMediatorWithOutOnlyTestCase.java
with Apache License 2.0
from wso2

@Test(groups = { "wso2.esb" })
public void outOnlyWithContentAwareMediatorTest() throws Exception {
    WireMonitorServer wireMonitorServer = new WireMonitorServer(3829);
    Map<String, String> headers = new HashMap<>();
    wireMonitorServer.start();
    headers.put(HttpHeaders.CONTENT_TYPE, "text/xml");
    headers.put(HTTPConstants.HEADER_SOAP_ACTION, "urn:placeOrder");
    HttpResponse response = HttpRequestUtil.doPost(new URL(getProxyServiceURLHttp("ESBJAVA4469WithLogMediator")), messageBody, headers);
    replacedert.replacedertEquals(response.getResponseCode(), HttpStatus.SC_ACCEPTED, "Response code should be 202");
    String outGoingMessage = wireMonitorServer.getCapturedMessage();
    replacedert.replacedertTrue(outGoingMessage.contains(">WSO2<"), "Outgoing message is empty or invalid content " + outGoingMessage);
}

19 Source : RiderDocumentation.java
with MIT License
from woowacourse-teams

public static RestDoreplacedentationResultHandler createDuplicatedRider() {
    return doreplacedent("rider/create-duplicated", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 Access Token 헤더"), headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-Type 헤더")), requestFields(fieldWithPath("race_id").type(NUMBER).description("해당 Rider가 참여한 Race ID")), getErrorResponseFields());
}

19 Source : RiderDocumentation.java
with MIT License
from woowacourse-teams

public static RestDoreplacedentationResultHandler updateRider() {
    return doreplacedent("rider/update-success", getDoreplacedentRequest(), getDoreplacedentResponse(), pathParameters(parameterWithName("riderId").description("Rider ID")), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 Access Token 헤더"), headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-Type 헤더")), requestFields(fieldWithPath("race_id").type(NUMBER).description("해당 Rider가 참여한 Race ID"), fieldWithPath("member_id").type(NUMBER).description("해당 Rider의 Member ID")), responseHeaders(headerWithName(HttpHeaders.LOCATION).description("Resource의 Location 헤더")));
}

19 Source : RiderDocumentation.java
with MIT License
from woowacourse-teams

public static RestDoreplacedentationResultHandler createRider() {
    return doreplacedent("rider/create-success", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 Access Token 헤더"), headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-Type 헤더")), requestFields(fieldWithPath("race_id").type(NUMBER).description("해당 Rider가 참여한 Race ID")), responseHeaders(headerWithName(HttpHeaders.LOCATION).description("Resource의 Location 헤더")));
}

19 Source : RaceDocumentation.java
with MIT License
from woowacourse-teams

public static RestDoreplacedentationResultHandler updateBadPathRace() {
    return doreplacedent("race/update-bad-path", getDoreplacedentRequest(), getDoreplacedentResponse(), pathParameters(parameterWithName("id").description("Race ID")), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 Access Token 헤더"), headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-Type 헤더")), requestFields(fieldWithPath("replacedle").type(STRING).description("레이스 제목"), fieldWithPath("description").type(STRING).description("레이스 세부내용"), fieldWithPath("race_duration").description("레이스 기간"), fieldWithPath("race_duration.start_date").attributes(getDateFormat()).description("레이스 시작 날짜"), fieldWithPath("race_duration.end_date").attributes(getDateFormat()).description("레이스 종료 날짜"), fieldWithPath("category").type(STRING).attributes(getRaceCategoryFormat()).description("레이스 종류"), fieldWithPath("certification").type(STRING).description("레이스 인증 예시"), fieldWithPath("thumbnail").type(STRING).description("레이스 썸네일 이미지"), subsectionWithPath("entrance_fee").type(STRING).description("레이스 입장료")), getErrorResponseFields());
}

19 Source : RaceDocumentation.java
with MIT License
from woowacourse-teams

public static RestDoreplacedentationResultHandler createRace() {
    return doreplacedent("race/create-success", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 Access Token 헤더"), headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-Type 헤더")), requestFields(fieldWithPath("replacedle").type(STRING).description("레이스 제목"), fieldWithPath("description").type(STRING).description("레이스 세부내용"), fieldWithPath("race_duration").description("레이스 기간"), fieldWithPath("race_duration.start_date").attributes(getDateFormat()).description("레이스 시작 날짜"), fieldWithPath("race_duration.end_date").attributes(getDateFormat()).description("레이스 종료 날짜"), fieldWithPath("category").type(STRING).attributes(getRaceCategoryFormat()).description("레이스 종류"), fieldWithPath("days").type(ARRAY).attributes(getDayFormat()).description("미션을 진행할 요일"), fieldWithPath("certification_available_duration").description("미션 인증이 가능한 시간"), fieldWithPath("certification_available_duration.start_time").attributes(getTimeFormat()).description("인증 시작 시간"), fieldWithPath("certification_available_duration.end_time").attributes(getTimeFormat()).description("인증 종료 시간"), subsectionWithPath("entrance_fee").type(STRING).description("레이스 입장료")), responseHeaders(headerWithName(HttpHeaders.LOCATION).description("Resource의 Location 헤더")));
}

19 Source : RaceDocumentation.java
with MIT License
from woowacourse-teams

public static RestDoreplacedentationResultHandler createBadRace() {
    return doreplacedent("race/create-fail", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 Access Token 헤더"), headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-Type 헤더")), requestFields(fieldWithPath("replacedle").type(NULL).description("레이스 제목"), fieldWithPath("description").type(NULL).description("레이스 세부내용"), fieldWithPath("race_duration").type(OBJECT).description("레이스 기간"), fieldWithPath("race_duration.start_date").type(STRING).attributes(getDateFormat()).description("레이스 시작 날짜"), fieldWithPath("race_duration.end_date").type(STRING).attributes(getDateFormat()).description("레이스 종료 날짜"), fieldWithPath("category").type(NULL).description("레이스 종류"), fieldWithPath("days").type(NULL).attributes(getDayFormat()).description("미션을 진행할 요일"), fieldWithPath("certification_available_duration").type(NULL).description("미션 인증이 가능한 시간"), subsectionWithPath("entrance_fee").type(NULL).description("레이스 입장료")), getErrorResponseFieldsWithFieldErrors());
}

19 Source : RaceDocumentation.java
with MIT License
from woowacourse-teams

public static RestDoreplacedentationResultHandler updateRace() {
    return doreplacedent("race/update-success", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 Access Token 헤더"), headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-Type 헤더")), pathParameters(parameterWithName("id").description("Race ID")), requestFields(fieldWithPath("replacedle").type(STRING).description("레이스 제목"), fieldWithPath("description").type(STRING).description("레이스 세부내용"), fieldWithPath("race_duration").description("레이스 기간"), fieldWithPath("race_duration.start_date").attributes(getDateFormat()).description("레이스 시작 날짜"), fieldWithPath("race_duration.end_date").attributes(getDateFormat()).description("레이스 종료 날짜"), fieldWithPath("category").type(STRING).attributes(getRaceCategoryFormat()).description("레이스 종류"), fieldWithPath("certification").type(STRING).description("레이스 인증 예시"), fieldWithPath("thumbnail").type(STRING).description("레이스 썸네일 이미지"), subsectionWithPath("entrance_fee").type(STRING).description("레이스 입장료")));
}

19 Source : MissionDocumentation.java
with MIT License
from woowacourse-teams

public static RestDoreplacedentationResultHandler createMission() {
    return doreplacedent("mission/create-success", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 Access Token 헤더"), headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-Type 헤더")), requestFields(fieldWithPath("mission_duration").description("미션 수행 가능 시간"), fieldWithPath("mission_duration.start_time").attributes(getDateTimeFormat()).description("미션 수행 시작 시간"), fieldWithPath("mission_duration.end_time").attributes(getDateTimeFormat()).description("미션 수행 종료 시간"), fieldWithPath("mission_instruction").type(STRING).description("미션 수행 방법"), fieldWithPath("race_id").type(NUMBER).description("미션의 레이스 id")), responseHeaders(headerWithName(HttpHeaders.LOCATION).description("Resource의 Location 헤더")));
}

19 Source : MissionDocumentation.java
with MIT License
from woowacourse-teams

public static RestDoreplacedentationResultHandler updateMission() {
    return doreplacedent("mission/update-success", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 Access Token 헤더"), headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-Type 헤더")), pathParameters(parameterWithName("id").description("Mission ID")), requestFields(fieldWithPath("mission_duration").description("미션 수행 가능 시간"), fieldWithPath("mission_duration.start_time").attributes(getDateTimeFormat()).description("미션 수행 시작 시간"), fieldWithPath("mission_duration.end_time").attributes(getDateTimeFormat()).description("미션 수행 종료 시간"), fieldWithPath("mission_instruction").type(STRING).description("미션 수행 방법"), fieldWithPath("race_id").type(NUMBER).description("미션의 레이스 id")));
}

19 Source : MemberDocumentation.java
with MIT License
from woowacourse-teams

public static RestDoreplacedentationResultHandler getAllMembers() {
    return doreplacedent("member/get-all-success", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 Access Token 헤더"), headerWithName(HttpHeaders.ACCEPT).description("Accept 헤더")), responseHeaders(headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-Type 헤더")), responseFields(subsectionWithPath("responses").type(ARRAY).description("Members 목록")));
}

19 Source : MemberDocumentation.java
with MIT License
from woowacourse-teams

public static RestDoreplacedentationResultHandler createBadCashUpdate() {
    return doreplacedent("member/update-cash-fail", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 Access Token 헤더"), headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-Type 헤더")), requestFields(fieldWithPath("cash").type(STRING).description("변경될 Member 보유 Cash")), getErrorResponseFieldsWithFieldErrors());
}

19 Source : MemberDocumentation.java
with MIT License
from woowacourse-teams

public static RestDoreplacedentationResultHandler updateCash() {
    return doreplacedent("member/update-cash", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 Access Token 헤더"), headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-Type 헤더")), requestFields(fieldWithPath("cash").type(STRING).description("변경될 Member 보유 Cash")), responseHeaders(headerWithName(HttpHeaders.LOCATION).description("Resource의 Location 헤더")));
}

19 Source : MemberDocumentation.java
with MIT License
from woowacourse-teams

public static RestDoreplacedentationResultHandler createBadMember() {
    return doreplacedent("member/create-fail", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 Access Token"), headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-Type Header")), getErrorResponseFieldsWithFieldErrors());
}

19 Source : MemberDocumentation.java
with MIT License
from woowacourse-teams

public static RestDoreplacedentationResultHandler updateName() {
    return doreplacedent("member/update-name", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 Access Token 헤더"), headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-Type 헤더")), requestFields(fieldWithPath("name").type(STRING).description("변경될 Member 이름")), responseHeaders(headerWithName(HttpHeaders.LOCATION).description("Resource의 Location 헤더")));
}

19 Source : MemberDocumentation.java
with MIT License
from woowacourse-teams

public static RestDoreplacedentationResultHandler getMember() {
    return doreplacedent("member/get-success", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 Access Token 헤더"), headerWithName(HttpHeaders.ACCEPT).description("Accept 헤더")), responseHeaders(headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-Type 헤더")), responseFields(fieldWithPath("id").type(NUMBER).description("Member id"), fieldWithPath("kakao_id").type(NUMBER).description("Member kakao id"), subsectionWithPath("profile").type(STRING).description("Member profile image url"), fieldWithPath("name").type(STRING).description("Member name"), fieldWithPath("email").type(STRING).attributes(getEmailFormat()).description("Member email"), subsectionWithPath("cash").type(STRING).description("Member cash"), fieldWithPath("role").type(STRING).attributes(getMemberRoleFormat()).description("Member role")));
}

19 Source : MemberDocumentation.java
with MIT License
from woowacourse-teams

public static RestDoreplacedentationResultHandler getMemberById() {
    return doreplacedent("member/get-by-id-success", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 Access Token 헤더"), headerWithName(HttpHeaders.ACCEPT).description("Accept 헤더")), pathParameters(parameterWithName("id").description("Member id")), responseHeaders(headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-Type 헤더")), responseFields(fieldWithPath("id").type(NUMBER).description("Member id"), fieldWithPath("kakao_id").type(NUMBER).description("Member kakao id"), subsectionWithPath("profile").type(STRING).description("Member profile image url"), fieldWithPath("name").type(STRING).description("Member name"), fieldWithPath("email").type(STRING).attributes(getEmailFormat()).description("Member email"), subsectionWithPath("cash").type(STRING).description("Member cash"), fieldWithPath("role").type(STRING).attributes(getMemberRoleFormat()).description("Member role")));
}

19 Source : MemberDocumentation.java
with MIT License
from woowacourse-teams

public static RestDoreplacedentationResultHandler updateProfileImage() {
    return doreplacedent("member/update-profile-image", getDoreplacedentRequest(), getDoreplacedentResponse(), requestHeaders(headerWithName(HttpHeaders.AUTHORIZATION).description("사용자 인증 Access Token 헤더"), headerWithName(HttpHeaders.CONTENT_TYPE).description("Content-Type 헤더")), requestParts(partWithName("profile_image").description("변경 될 Profile Image")), responseHeaders(headerWithName(HttpHeaders.CONTENT_TYPE).description("Response Content Type 헤더")), responseFields(fieldWithPath("image_url").type(STRING).description("수정된 이미지 url")));
}

19 Source : HttpClientUtils.java
with Apache License 2.0
from vipshop

public static ResponseEnreplacedy sendDeleteResponseJson(String url) throws IOException {
    CloseableHttpClient httpClient = null;
    try {
        httpClient = HttpClientBuilder.create().build();
        HttpDelete request = new HttpDelete(url);
        final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000).setSocketTimeout(10000).build();
        request.setConfig(requestConfig);
        request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        CloseableHttpResponse response = httpClient.execute(request);
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        return new ResponseEnreplacedy(response.getStatusLine().getStatusCode(), enreplacedy != null ? EnreplacedyUtils.toString(enreplacedy) : null);
    } finally {
        HttpUtils.closeHttpClientQuietly(httpClient);
    }
}

19 Source : HttpClientUtils.java
with Apache License 2.0
from vipshop

public static ResponseEnreplacedy sendPostRequestJson(String url, String jsonBody) throws IOException {
    CloseableHttpClient httpClient = null;
    try {
        httpClient = HttpClientBuilder.create().build();
        HttpPost request = new HttpPost(url);
        final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000).setSocketTimeout(10000).build();
        request.setConfig(requestConfig);
        StringEnreplacedy params = new StringEnreplacedy(jsonBody);
        request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        request.setEnreplacedy(params);
        CloseableHttpResponse response = httpClient.execute(request);
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        return new ResponseEnreplacedy(response.getStatusLine().getStatusCode(), enreplacedy != null ? EnreplacedyUtils.toString(enreplacedy) : null);
    } finally {
        HttpUtils.closeHttpClientQuietly(httpClient);
    }
}

19 Source : HttpClientUtils.java
with Apache License 2.0
from vipshop

public static ResponseEnreplacedy sendGetRequestJson(String url) throws IOException {
    CloseableHttpClient httpClient = null;
    try {
        httpClient = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(url);
        final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000).setSocketTimeout(10000).build();
        request.setConfig(requestConfig);
        request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        CloseableHttpResponse response = httpClient.execute(request);
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        return new ResponseEnreplacedy(response.getStatusLine().getStatusCode(), enreplacedy != null ? EnreplacedyUtils.toString(enreplacedy) : null);
    } finally {
        HttpUtils.closeHttpClientQuietly(httpClient);
    }
}

19 Source : HttpClientUtils.java
with Apache License 2.0
from vipshop

public static ResponseEnreplacedy sendPutRequestJson(String url, String jsonBody) throws IOException {
    CloseableHttpClient httpClient = null;
    try {
        httpClient = HttpClientBuilder.create().build();
        HttpPut request = new HttpPut(url);
        final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000).setSocketTimeout(10000).build();
        request.setConfig(requestConfig);
        StringEnreplacedy params = new StringEnreplacedy(jsonBody);
        request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        request.setEnreplacedy(params);
        CloseableHttpResponse response = httpClient.execute(request);
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        return new ResponseEnreplacedy(response.getStatusLine().getStatusCode(), enreplacedy != null ? EnreplacedyUtils.toString(enreplacedy) : null);
    } finally {
        HttpUtils.closeHttpClientQuietly(httpClient);
    }
}

19 Source : UpdateJobCronUtils.java
with Apache License 2.0
from vipshop

/**
 * Send update job cron request to UpdateJobCron API in Console.
 */
public static void updateJobCron(String namespace, String jobName, String cron, Map<String, String> customContext) throws SaturnJobException {
    for (int i = 0, size = SystemEnvProperties.VIP_SATURN_CONSOLE_URI_LIST.size(); i < size; i++) {
        String consoleUri = SystemEnvProperties.VIP_SATURN_CONSOLE_URI_LIST.get(i);
        String targetUrl = consoleUri + "/rest/v1/" + namespace + "/jobs/" + jobName + "/cron";
        LogUtils.info(log, jobName, "update job cron of domain {} to url {}: {}, retry count: {}", namespace, targetUrl, cron, i);
        CloseableHttpClient httpClient = null;
        try {
            checkParameters(cron);
            Map<String, String> bodyEnreplacedy = Maps.newHashMap();
            if (customContext != null) {
                bodyEnreplacedy.putAll(customContext);
            }
            bodyEnreplacedy.put("cron", cron);
            String json = JsonUtils.toJson(bodyEnreplacedy, new TypeToken<Map<String, String>>() {
            }.getType());
            // prepare
            httpClient = HttpClientBuilder.create().build();
            HttpPut request = new HttpPut(targetUrl);
            final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(10000).build();
            request.setConfig(requestConfig);
            StringEnreplacedy params = new StringEnreplacedy(json);
            request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
            request.setEnreplacedy(params);
            CloseableHttpResponse httpResponse = httpClient.execute(request);
            HttpUtils.handleResponse(httpResponse);
            return;
        } catch (SaturnJobException se) {
            LogUtils.error(log, jobName, "SaturnJobException throws: {}", se.getMessage(), se);
            throw se;
        } catch (ConnectException e) {
            LogUtils.error(log, jobName, "Fail to connect to url:{}, throws: {}", targetUrl, e.getMessage(), e);
            if (i == size - 1) {
                throw new SaturnJobException(SaturnJobException.SYSTEM_ERROR, "no available console server", e);
            }
        } catch (Exception e) {
            LogUtils.error(log, jobName, "Other exception throws: {}", e.getMessage(), e);
            throw new SaturnJobException(SaturnJobException.SYSTEM_ERROR, e.getMessage(), e);
        } finally {
            HttpUtils.closeHttpClientQuietly(httpClient);
        }
    }
}

19 Source : AlarmUtils.java
with Apache License 2.0
from vipshop

/**
 * Send alarm request to Alarm API in Console.
 */
public static void raiseAlarm(Map<String, Object> alarmInfo, String namespace) throws SaturnJobException {
    int size = SystemEnvProperties.VIP_SATURN_CONSOLE_URI_LIST.size();
    for (int i = 0; i < size; i++) {
        String consoleUri = SystemEnvProperties.VIP_SATURN_CONSOLE_URI_LIST.get(i);
        String targetUrl = consoleUri + "/rest/v1/" + namespace + "/alarms/raise";
        LogUtils.info(log, LogEvents.ExecutorEvent.COMMON, "raise alarm of domain {} to url {}: {}, retry count: {}", namespace, targetUrl, alarmInfo.toString(), i);
        CloseableHttpClient httpClient = null;
        try {
            checkParameters(alarmInfo);
            // prepare
            httpClient = HttpClientBuilder.create().build();
            HttpPost request = new HttpPost(targetUrl);
            final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(10000).build();
            request.setConfig(requestConfig);
            StringEnreplacedy params = new StringEnreplacedy(JsonUtils.getGson().toJson(alarmInfo, new TypeToken<Map<String, Object>>() {
            }.getType()));
            request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
            request.setEnreplacedy(params);
            // send request
            CloseableHttpResponse httpResponse = httpClient.execute(request);
            // handle response
            HttpUtils.handleResponse(httpResponse);
            return;
        } catch (SaturnJobException se) {
            LogUtils.error(log, LogEvents.ExecutorEvent.COMMON, "SaturnJobException throws: {}", se.getMessage(), se);
            throw se;
        } catch (ConnectException e) {
            LogUtils.error(log, LogEvents.ExecutorEvent.COMMON, "Fail to connect to url:{}, throws: {}", targetUrl, e.getMessage(), e);
            if (i == size - 1) {
                throw new SaturnJobException(SaturnJobException.SYSTEM_ERROR, "no available console server", e);
            }
        } catch (Exception e) {
            LogUtils.error(log, LogEvents.ExecutorEvent.COMMON, "Other exception throws: {}", e.getMessage(), e);
            throw new SaturnJobException(SaturnJobException.SYSTEM_ERROR, e.getMessage(), e);
        } finally {
            HttpUtils.closeHttpClientQuietly(httpClient);
        }
    }
}

19 Source : AbstractElasticJob.java
with Apache License 2.0
from vipshop

private void runDownStream(final JobExecutionMultipleShardingContext shardingContext) {
    if (configService.isLocalMode()) {
        return;
    }
    JobType jobType = configService.getJobType();
    if (!(jobType.isCron() || jobType.isPreplacedive())) {
        return;
    }
    if (shardingContext.getShardingTotalCount() != 1) {
        return;
    }
    List<String> downStream = configService.getDownStream();
    if (downStream.isEmpty()) {
        return;
    }
    if (!mayRunDownStream(shardingContext)) {
        return;
    }
    String downStreamDataStr = scheduler.getTrigger().serializeDownStreamData(shardingContext.getTriggered());
    String logMessagePrefix = "call runDownStream api";
    int size = SystemEnvProperties.VIP_SATURN_CONSOLE_URI_LIST.size();
    for (int i = 0; i < size; i++) {
        String consoleUri = SystemEnvProperties.VIP_SATURN_CONSOLE_URI_LIST.get(i);
        String targetUrl = consoleUri + "/rest/v1/" + namespace + "/jobs/" + jobName + "/runDownStream";
        LogUtils.info(log, jobName, "{}, target url is {}", logMessagePrefix, targetUrl);
        CloseableHttpClient httpClient = null;
        try {
            httpClient = HttpClientBuilder.create().build();
            HttpPost request = new HttpPost(targetUrl);
            final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(10000).build();
            request.setConfig(requestConfig);
            request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
            request.setEnreplacedy(new StringEnreplacedy(downStreamDataStr));
            CloseableHttpResponse httpResponse = httpClient.execute(request);
            StatusLine statusLine = httpResponse.getStatusLine();
            if (statusLine != null && statusLine.getStatusCode() == HttpStatus.SC_OK) {
                HttpEnreplacedy enreplacedy = httpResponse.getEnreplacedy();
                String result = enreplacedy != null ? EnreplacedyUtils.toString(enreplacedy, "UTF-8") : null;
                LogUtils.info(log, jobName, "{}, result is {}", logMessagePrefix, result);
                return;
            } else {
                LogUtils.info(log, jobName, "{} failed, StatusLine is {}", logMessagePrefix, statusLine);
            }
        } catch (Exception e) {
            LogUtils.error(log, jobName, "{} error", logMessagePrefix, e);
        } finally {
            HttpClientUtils.closeQuietly(httpClient);
        }
    }
}

19 Source : Initializer.java
with Apache License 2.0
from tum-gis

public static void httpPost() throws ClientProtocolException, IOException {
    // Check if datasource connection details exist in application.yml
    Yaml yaml = new Yaml();
    Reader yamlFile = new FileReader("application.yml");
    Map<String, Object> yamlMaps = (Map<String, Object>) yaml.load(yamlFile);
    Object obj = yamlMaps.get("datasource-connection");
    // check the datasource name. If it is ThingSpeak, datasource type is Thingspeak
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = mapper.convertValue(obj, JsonNode.clreplaced);
    JsonNode jsonNodeDataSource = null;
    // HTTP POST with the defined datasourceconnection
    String connectionType = jsonNode.get("connectionType").toString();
    String datasourceType = null;
    switch(connectionType) {
        case "\"Thingspeak\"":
            datasourceType = "thingspeak";
            ThingspeakConnection thingspeakConnection = mapper.convertValue(obj, ThingspeakConnection.clreplaced);
            jsonNodeDataSource = mapper.convertValue(thingspeakConnection, JsonNode.clreplaced);
            break;
        case "\"SensorThings\"":
            datasourceType = "sensorThings";
            SensorThingsConnection sensorThingsConnection = mapper.convertValue(obj, SensorThingsConnection.clreplaced);
            jsonNodeDataSource = mapper.convertValue(sensorThingsConnection, JsonNode.clreplaced);
            break;
        case "\"OpenSensors\"":
            datasourceType = "openSensors";
            OpenSensorsConnection openSensorsConnection = mapper.convertValue(obj, OpenSensorsConnection.clreplaced);
            jsonNodeDataSource = mapper.convertValue(openSensorsConnection, JsonNode.clreplaced);
            break;
        case "\"CSV\"":
            datasourceType = "csv";
            CsvConnection csvConnection = mapper.convertValue(obj, CsvConnection.clreplaced);
            jsonNodeDataSource = mapper.convertValue(csvConnection, JsonNode.clreplaced);
            break;
        case "\"C3ntinel\"":
            datasourceType = "c3ntinel";
            C3ntinelConnection c3ntinelConnection = mapper.convertValue(obj, C3ntinelConnection.clreplaced);
            jsonNodeDataSource = mapper.convertValue(c3ntinelConnection, JsonNode.clreplaced);
            break;
        case "\"Twitter\"":
            datasourceType = "twitter";
            TwitterConnection twitterConnection = mapper.convertValue(obj, TwitterConnection.clreplaced);
            jsonNodeDataSource = mapper.convertValue(twitterConnection, JsonNode.clreplaced);
            break;
        case "\"Ixsi\"":
            datasourceType = "ixsi";
            IxsiConnection ixsiConnection = mapper.convertValue(obj, IxsiConnection.clreplaced);
            jsonNodeDataSource = mapper.convertValue(ixsiConnection, JsonNode.clreplaced);
            break;
    }
    HttpClient httpClient = new DefaultHttpClient();
    String postUrl = "http://" + SpringHost.getHostAddress() + ":" + SpringHost.getPort() + "/" + datasourceType;
    HttpPost httpPost = new HttpPost(postUrl);
    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    try {
        StringEnreplacedy stringEnreplacedy = new StringEnreplacedy(jsonNodeDataSource.toString());
        httpPost.getRequestLine();
        httpPost.setEnreplacedy(stringEnreplacedy);
        httpClient.execute(httpPost);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

19 Source : ODataUpdateTests.java
with Apache License 2.0
from syndesisio

private static void updateProperty(String serviceURI, String resourcePath, String keyPredicate, String property, String value) throws Exception {
    URI httpURI = URI.create(serviceURI + FORWARD_SLASH + resourcePath + OPEN_BRACKET + QUOTE_MARK + keyPredicate + QUOTE_MARK + CLOSE_BRACKET);
    ObjectNode node = OBJECT_MAPPER.createObjectNode();
    node.put(property, value);
    String data = OBJECT_MAPPER.writeValuereplacedtring(node);
    HttpPatch request = new HttpPatch(httpURI);
    StringEnreplacedy httpEnreplacedy = new StringEnreplacedy(data, org.apache.http.enreplacedy.ContentType.APPLICATION_JSON);
    httpEnreplacedy.setChunked(false);
    request.setEnreplacedy(httpEnreplacedy);
    Header contentTypeHeader = request.getEnreplacedy().getContentType();
    ContentType contentType = ContentType.parse(contentTypeHeader.getValue());
    request.addHeader(HttpHeaders.ACCEPT, "application/json;odata.metadata=full,application/xml,*/*");
    request.addHeader(HttpHeaders.ACCEPT_CHARSET, Constants.UTF8.toLowerCase());
    request.addHeader(HttpHeaders.CONTENT_TYPE, contentType.toString());
    request.addHeader(HttpHeader.ODATA_VERSION, ODataServiceVersion.V40.toString());
    request.addHeader(HttpHeader.ODATA_MAX_VERSION, ODataServiceVersion.V40.toString());
    try (CloseableHttpClient client = HttpClients.createMinimal();
        CloseableHttpResponse response = client.execute(request)) {
        StatusLine statusLine = response.getStatusLine();
        replacedertEquals(HttpStatus.SC_NO_CONTENT, statusLine.getStatusCode());
    }
}

19 Source : HttpClientInstance.java
with Apache License 2.0
from sofastack

public String executeGet(String url) throws Exception {
    if (StringUtils.isBlank(url)) {
        return null;
    }
    if (!url.startsWith("http://")) {
        url = "http://" + url;
    }
    HttpGet httpget = new HttpGet(url);
    httpget.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    httpget.setConfig(defaultRequestConfig);
    return this.execute(httpget);
}

19 Source : HttpClientInstance.java
with Apache License 2.0
from sofastack

public String executeHead(String url) throws Exception {
    if (StringUtils.isBlank(url)) {
        return null;
    }
    if (!url.startsWith("http://")) {
        url = "http://" + url;
    }
    HttpHead httpHead = new HttpHead(url);
    httpHead.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    httpHead.setConfig(defaultRequestConfig);
    return this.execute(httpHead);
}

19 Source : HttpObserver.java
with Apache License 2.0
from sofastack

void report2Agent(Address agentAddress, String msg, Map<String, String> metadata) {
    HttpPost httpPost = new HttpPost(buildRealAgentServerURL(agentAddress));
    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, TEXT_MEDIATYPE);
    try {
        httpPost.setEnreplacedy(new StringEnreplacedy(msg));
    } catch (UnsupportedEncodingException e) {
        logger.info(">>WARNING: report msg encoding err:{}", e.getMessage());
    }
    sendHttpDataSilently(httpPost, metadata);
}

19 Source : HttpObserver.java
with Apache License 2.0
from sofastack

void reportSnappy2Agent(Address agentAddress, String msg, Map<String, String> metadata) {
    HttpPost httpPost = new HttpPost(buildRealAgentServerURL(agentAddress));
    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_OCTET_STREAM);
    httpPost.setHeader(HttpHeaders.CONTENT_ENCODING, SNAPPY);
    byte[] compressed = new byte[0];
    try {
        compressed = Snappy.compress(msg, Charset.forName(UTF_8));
    } catch (IOException e) {
        logger.info(">>WARNING: snappy compress report msg err:{}", e.getMessage());
        return;
    }
    httpPost.setEnreplacedy(new ByteArrayEnreplacedy(compressed));
    sendHttpDataSilently(httpPost, metadata);
}

19 Source : AbstractRotator.java
with Apache License 2.0
from silentbalanceyh

protected void configHeader(final HttpRequestBase request, final JsonObject headers) {
    if (!headers.containsKey(HttpHeaders.CONTENT_TYPE)) {
        request.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    }
    if (Ut.notNil(headers)) {
        headers.stream().filter(item -> Objects.nonNull(item.getValue())).forEach(item -> request.addHeader(item.getKey(), item.getValue().toString()));
    }
}

19 Source : HttpClientTools.java
with Apache License 2.0
from sedmelluq

public static String getRawContentType(HttpResponse response) {
    Header header = response.getFirstHeader(HttpHeaders.CONTENT_TYPE);
    return header != null ? header.getValue() : null;
}

19 Source : SingleRequestSender.java
with MIT License
from ria-ee

private static MimeHeaders getMimeHeaders(String contentType) {
    MimeHeaders mimeHeaders = new MimeHeaders();
    mimeHeaders.addHeader(HttpHeaders.CONTENT_TYPE, contentType);
    return mimeHeaders;
}

19 Source : WsdlRequestProcessorTest.java
with MIT License
from ria-ee

@Test
public void shouldGetWsdl() throws Exception {
    // setup
    mockServer.stubFor(WireMock.any(urlPathEqualTo(EXPECTED_WSDL_QUERY_PATH)).willReturn(aResponse().withBodyFile("wsdl_response.xml").withHeader(HttpHeaders.CONTENT_TYPE, MULTIPART_RELATED + "; type=\"text/xml\"; charset=UTF-8; boundary=xroadZTLLyIMMYnAYliBumWCqHJYAhutxNf")));
    mockServer.start();
    final SecurityServerId providedIdentifier = SecurityServerId.create(EXPECTED_XR_INSTANCE, "memberClreplacedGov", "memberCode11", "serverCode_");
    ServerConf.reload(new TestServerConf() {

        @Override
        public SecurityServerId getIdentifier() {
            return providedIdentifier;
        }
    });
    final ServiceId expectedServiceId = ServiceId.create(EXPECTED_XR_INSTANCE, "someMember", "serviceCode3322", "subsystem3", "serviceCode3", "version1.1");
    when(mockRequest.getParameter(eq(WsdlRequestProcessor.PARAM_INSTANCE_IDENTIFIER))).thenReturn(expectedServiceId.getXRoadInstance());
    when(mockRequest.getParameter(eq(WsdlRequestProcessor.PARAM_MEMBER_CLreplaced))).thenReturn(expectedServiceId.getMemberClreplaced());
    when(mockRequest.getParameter(eq(WsdlRequestProcessor.PARAM_MEMBER_CODE))).thenReturn(expectedServiceId.getMemberCode());
    when(mockRequest.getParameter(eq(WsdlRequestProcessor.PARAM_SERVICE_CODE))).thenReturn(expectedServiceId.getServiceCode());
    when(mockRequest.getParameter(eq(WsdlRequestProcessor.PARAM_SUBSYSTEM_CODE))).thenReturn(expectedServiceId.getSubsystemCode());
    when(mockRequest.getParameter(eq(WsdlRequestProcessor.PARAM_VERSION))).thenReturn(expectedServiceId.getServiceVersion());
    final List<String> expectedWSDLServiceNames = Arrays.asList("getRandom", "helloService");
    WsdlRequestProcessor processorToTest = new WsdlRequestProcessor(mockRequest, mockResponse);
    // execution
    processorToTest.process();
    // verification
    replacedertContentTypeIsIn(singletonList(TEXT_XML));
    Definition definition = WSDLFactory.newInstance().newWSDLReader().readWSDL(null, new InputSource(mockServletOutputStream.getAsInputStream()));
    List<String> operationNames = parseOperationNamesFromWSDLDefinition(definition);
    replacedertThat("Expected to find certain operations", operationNames, containsInAnyOrder(expectedWSDLServiceNames.toArray()));
}

19 Source : WsdlRequestProcessorTest.java
with MIT License
from ria-ee

@Test
public void shouldThrowWhenReceivingSoapFault() throws Exception {
    // setup
    final String expectedMessage = "That was an invalid request, buddy!";
    final String expectedErrorCode = X_INVALID_REQUEST;
    final CodedException generatedEx = new CodedException(expectedErrorCode, expectedMessage);
    mockServer.stubFor(WireMock.any(urlPathEqualTo(EXPECTED_WSDL_QUERY_PATH)).willReturn(aResponse().withBody(SoapFault.createFaultXml(generatedEx).getBytes(MimeUtils.UTF8)).withHeader(HttpHeaders.CONTENT_TYPE, TEXT_XML_UTF8)));
    mockServer.start();
    final SecurityServerId providedIdentifier = SecurityServerId.create(EXPECTED_XR_INSTANCE, "memberClreplacedGov", "memberCode11", "serverCode_");
    ServerConf.reload(new TestServerConf() {

        @Override
        public SecurityServerId getIdentifier() {
            return providedIdentifier;
        }
    });
    final CentralServiceId expectedCentralServiceId = CentralServiceId.create(EXPECTED_XR_INSTANCE, "serviceCode3322");
    when(mockRequest.getParameter(eq(WsdlRequestProcessor.PARAM_INSTANCE_IDENTIFIER))).thenReturn(expectedCentralServiceId.getXRoadInstance());
    when(mockRequest.getParameter(eq(WsdlRequestProcessor.PARAM_SERVICE_CODE))).thenReturn(expectedCentralServiceId.getServiceCode());
    WsdlRequestProcessor processorToTest = new WsdlRequestProcessor(mockRequest, mockResponse);
    thrown.expect(CodedException.clreplaced);
    thrown.expect(faultCodeEquals(expectedErrorCode));
    thrown.expectMessage(allOf(containsString(expectedErrorCode), containsString(expectedMessage)));
    // execution
    processorToTest.process();
// expecting an exception..
}

19 Source : WsdlRequestProcessorTest.java
with MIT License
from ria-ee

@Test
public void shouldCreateConnection() throws Exception {
    // setup
    SoapMessageImpl mockSoapMessage = mock(SoapMessageImpl.clreplaced);
    mockServer.stubFor(WireMock.any(urlPathEqualTo(EXPECTED_WSDL_QUERY_PATH)).willReturn(aResponse()));
    mockServer.start();
    final String expectedMessage = "expectedMessage135122";
    when(mockSoapMessage.getBytes()).thenReturn(expectedMessage.getBytes());
    WsdlRequestProcessor processorToTest = new WsdlRequestProcessor(mockRequest, mockResponse);
    // execution
    processorToTest.createConnection(mockSoapMessage);
    // verification
    mockServer.verify(postRequestedFor(urlEqualTo(EXPECTED_WSDL_QUERY_PATH)).withHeader(HttpHeaders.CONTENT_TYPE, equalTo(TEXT_XML_UTF8)).withRequestBody(equalTo(expectedMessage)));
}

19 Source : ReportPortalErrorHandler.java
with Apache License 2.0
from reportportal

private boolean isNotJson(Response<ByteSource> rs) {
    boolean result = true;
    Collection<String> contentTypes = rs.getHeaders().get(HttpHeaders.CONTENT_TYPE);
    if (contentTypes.isEmpty() && rs.getHeaders().containsKey(HttpHeaders.CONTENT_TYPE.toLowerCase())) {
        contentTypes = rs.getHeaders().get(HttpHeaders.CONTENT_TYPE.toLowerCase());
    }
    if (null != contentTypes) {
        for (String contentType : contentTypes) {
            boolean isJson = contentType.contains(ContentType.APPLICATION_JSON.getMimeType());
            if (isJson) {
                result = false;
                break;
            }
        }
    }
    return result;
}

19 Source : HwYunMsgSender.java
with MIT License
from rememberber

@Override
public SendResult send(String[] msgData) {
    SendResult sendResult = new SendResult();
    try {
        // APP接入地址+接口访问URI
        String url = App.config.getHwAccessUrl();
        // APP_Key
        String appKey = App.config.getHwAppKey();
        // APP_Secret
        String appSecret = App.config.getHwAppSecretPreplacedword();
        // 国内短信签名通道号或国际/港澳台短信通道号
        String sender = App.config.getHwSenderCode();
        String signature = App.config.getHwSignature();
        // 模板ID
        String templateId = HwYunMsgMaker.templateId;
        // 模板变量
        String templateParas = JSONUtil.toJsonStr(hwYunMsgMaker.makeMsg(msgData));
        String receiver = msgData[0];
        if (PushControl.dryRun) {
            sendResult.setSuccess(true);
            return sendResult;
        } else {
            // 请求Body,不携带签名名称时,signature请填null
            String body = buildRequestBody(sender, receiver, templateId, templateParas, "", signature);
            if (null == body || body.isEmpty()) {
                sendResult.setSuccess(false);
                sendResult.setInfo("body is null.");
                log.error("body is null.");
                return sendResult;
            }
            // 请求Headers中的X-WSSE参数值
            String wsseHeader = buildWsseHeader(appKey, appSecret);
            if (null == wsseHeader || wsseHeader.isEmpty()) {
                sendResult.setSuccess(false);
                sendResult.setInfo("wsse header is null.");
                log.error("wsse header is null.");
                return sendResult;
            }
            HttpResponse response = closeableHttpClient.execute(RequestBuilder.create("POST").setUri(url).addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded").addHeader(HttpHeaders.AUTHORIZATION, AUTH_HEADER_VALUE).addHeader("X-WSSE", wsseHeader).setEnreplacedy(new StringEnreplacedy(body)).build());
            // System.out.println(response.toString()); //打印响应头域信息
            // System.out.println(EnreplacedyUtils.toString(response.getEnreplacedy())); //打印响应消息实体
            // if (result.result == 0) {
            sendResult.setSuccess(true);
        // } else {
        // sendResult.setSuccess(false);
        // sendResult.setInfo(result.toString());
        // }
        }
    } catch (Exception e) {
        sendResult.setSuccess(false);
        sendResult.setInfo(e.getMessage());
        log.error(ExceptionUtils.getStackTrace(e));
    }
    return sendResult;
}

19 Source : Slack.java
with GNU General Public License v2.0
from Rails-18xx

public void sendMessage(String player) {
    setConfig();
    if (webhook == null) {
        return;
    }
    Map<String, String> keys = new HashMap<>();
    keys.put("game", root.getGameName());
    // keys.put("gameName", StringUtils.defaultIfBlank(root.getGameData().getUsersGameName(), "[none]"));
    keys.put("round", gameUiManager.getCurrentRound().getRoundName());
    keys.put("current", StringUtils.defaultIfBlank(playerNameMappings.get(player), player));
    keys.put("previous", StringUtils.defaultIfBlank(observer.getFormerPlayer().getId(), "[none]"));
    String msgBody = StringSubsreplacedutor.replace(body, keys);
    log.debug("Sending message '{}' to Slack for user {}", msgBody, player);
    HttpPost httpPost = new HttpPost(webhook);
    try {
        httpPost.setEnreplacedy(new StringEnreplacedy(msgBody));
        httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        httpPost.setHeader(HttpHeaders.USER_AGENT, "18xx Rails");
        CloseableHttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) {
            // TODO: verify result
            log.debug("Unexpected Slack response: {}", response);
        }
        response.close();
    } catch (IOException e) {
        log.error("Error sending message to Slack", e);
    }
}

19 Source : Discord.java
with GNU General Public License v2.0
from Rails-18xx

public void sendMessage(String player) {
    setConfig();
    if (webhook == null) {
        return;
    }
    Map<String, String> keys = new HashMap<>();
    keys.put("game", root.getGameName());
    // keys.put("gameName", StringUtils.defaultIfBlank(root.getGameData().getUsersGameName(), "[none]"));
    keys.put("round", gameUiManager.getCurrentRound().getRoundName());
    keys.put("current", StringUtils.defaultIfBlank(playerNameMappings.get(player), player));
    keys.put("previous", StringUtils.defaultIfBlank(observer.getFormerPlayer().getId(), "[none]"));
    String msgBody = StringSubsreplacedutor.replace(body, keys);
    log.debug("Sending message '{}' to Discord for user {}", msgBody, player);
    HttpPost httpPost = new HttpPost(webhook);
    try {
        httpPost.setEnreplacedy(new StringEnreplacedy(msgBody));
        httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        httpPost.setHeader(HttpHeaders.USER_AGENT, "18xx Rails");
        CloseableHttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) {
            log.debug("Unexpected Discord  response: {}", response);
        }
        response.close();
    } catch (IOException e) {
        log.error("Error sending message to Discord", e);
    }
}

19 Source : GetRestConfigFileServlet.java
with MIT License
from qunarcorp

private void writeFile(HttpServletResponse resp, RestFile restFile) throws IOException {
    resp.addHeader(Constants.VERSION_NAME, String.valueOf(restFile.getVersion()));
    resp.addHeader(Constants.CHECKSUM_NAME, restFile.getChecksum());
    resp.setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=utf-8");
    resp.getWriter().write(restFile.getData());
    resp.flushBuffer();
}

19 Source : GetRestConfigFileServlet.java
with MIT License
from qunarcorp

private void writeStatusResponse(HttpServletResponse resp, int statusCode, RestApiResponse restApiResponse) throws IOException {
    resp.setStatus(statusCode);
    resp.setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=utf-8");
    resp.getWriter().write(jsonMapper.serialize(restApiResponse));
    resp.flushBuffer();
}

19 Source : HttpResponseResource.java
with BSD 2-Clause "Simplified" License
from PushFish

public String getContentType() {
    final Header header = response.getFirstHeader(HttpHeaders.CONTENT_TYPE);
    return header == null ? null : header.getValue();
}

19 Source : KeycloakRequiredActionLinkUtil.java
with MIT License
from project-sunbird

public static String getAdminAccessToken(RequestContext context) throws Exception {
    Map<String, String> headers = new HashMap<>();
    headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
    String url = ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_URL) + "realms/" + ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_RELAM) + "/protocol/openid-connect/token";
    Map<String, String> fields = new HashMap<>();
    fields.put("client_id", ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_CLIENT_ID));
    fields.put("client_secret", ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_CLIENT_SECRET));
    fields.put("grant_type", "client_credentials");
    String response = HttpClientUtil.postFormData(url, fields, headers);
    logger.info(context, "KeycloakRequiredActionLinkUtil:getAdminAccessToken: Response = " + response);
    Map<String, Object> responseMap = new ObjectMapper().readValue(response, Map.clreplaced);
    return (String) responseMap.get(ACCESS_TOKEN);
}

19 Source : KeycloakRequiredActionLinkUtil.java
with MIT License
from project-sunbird

private static String generateLink(Map<String, String> request, RequestContext context) throws Exception {
    Map<String, String> headers = new HashMap<>();
    headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    headers.put(JsonKey.AUTHORIZATION, JsonKey.BEARER + getAdminAccessToken(context));
    logger.info(context, "KeycloakRequiredActionLinkUtil:generateLink: complete URL " + ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_URL) + "realms/" + ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_RELAM) + SUNBIRD_KEYCLOAK_REQD_ACTION_LINK);
    logger.info(context, "KeycloakRequiredActionLinkUtil:generateLink: request body " + mapper.writeValuereplacedtring(request));
    String url = ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_URL) + "realms/" + ProjectUtil.getConfigValue(JsonKey.SUNBIRD_SSO_RELAM) + SUNBIRD_KEYCLOAK_REQD_ACTION_LINK;
    String response = HttpClientUtil.post(url, mapper.writeValuereplacedtring(request), headers);
    logger.info(context, "KeycloakRequiredActionLinkUtil:generateLink: Response = " + response);
    Map<String, Object> responseMap = new ObjectMapper().readValue(response, Map.clreplaced);
    return (String) responseMap.get(LINK);
}

19 Source : HttpClient.java
with Apache License 2.0
from polkadot-java

public static HttpResp put(String url, Params params, HeadOptions options) throws Exception {
    if (options == null) {
        options = HeadOptions.build();
    }
    String sendUrl = buildUrl(url, params);
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpPut put = new HttpPut(sendUrl);
        if (params != null) {
            HttpEnreplacedy enreplacedy = params.toEnreplacedy(options.getHeaderValue(HttpHeaders.CONTENT_TYPE));
            put.setEnreplacedy(enreplacedy);
        }
        put.setConfig(options.getRequestConfig());
        options.getHeaders().forEach(header -> put.addHeader(header));
        final HeadOptions o = options;
        return client.execute(put, response -> {
            int status = response.getStatusLine().getStatusCode();
            HttpEnreplacedy enreplacedy = response.getEnreplacedy();
            String body = enreplacedy != null ? EnreplacedyUtils.toString(enreplacedy, o.encoding) : null;
            return new HttpResp(status, body);
        });
    }
}

19 Source : HttpClient.java
with Apache License 2.0
from polkadot-java

public static HttpResp post(String url, Params params, HeadOptions options) throws Exception {
    if (options == null) {
        options = HeadOptions.build();
    }
    String sendUrl = buildUrl(url, params);
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpPost post = new HttpPost(sendUrl);
        if (params != null) {
            HttpEnreplacedy enreplacedy = params.toEnreplacedy(options.getHeaderValue(HttpHeaders.CONTENT_TYPE));
            post.setEnreplacedy(enreplacedy);
        }
        post.setConfig(options.getRequestConfig());
        options.getHeaders().forEach(header -> post.addHeader(header));
        final HeadOptions o = options;
        return client.execute(post, response -> {
            int status = response.getStatusLine().getStatusCode();
            HttpEnreplacedy enreplacedy = response.getEnreplacedy();
            String body = enreplacedy != null ? EnreplacedyUtils.toString(enreplacedy, o.encoding) : null;
            return new HttpResp(status, body);
        });
    }
}

See More Examples