Java Code Examples for org.apache.http.entity.StringEntity#setContentEncoding()

The following examples show how to use org.apache.http.entity.StringEntity#setContentEncoding() . 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: MixerHttpClient.java    From beam-client-java with MIT License 7 votes vote down vote up
private HttpEntity makeEntity(Object... args) {
    Object object = args.length == 1 ? args[0] : args;
    String serialized = this.mixer.gson.toJson(object);

    try {
        StringEntity e = new StringEntity(serialized);
        e.setContentEncoding("UTF-8");
        e.setContentType("application/json");

        return e;
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }

    return null;
}
 
Example 2
Source File: ServiceTestController.java    From saluki with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "testService", method = RequestMethod.POST)
public Object testService(@RequestParam(value = "ipPort", required = true) String ipPort,
    @RequestBody GrpcServiceTestModel model) throws Exception {
  String serviceUrl = "http://" + ipPort + "/service/test";
  HttpPost request = new HttpPost(serviceUrl);
  request.addHeader("content-type", "application/json");
  request.addHeader("Accept", "application/json");
  try {
    StringEntity entity = new StringEntity(gson.toJson(model), "utf-8");
    entity.setContentEncoding("UTF-8");
    entity.setContentType("application/json");
    request.setEntity(entity);
    HttpResponse httpResponse = httpClient.execute(request);
    if (httpResponse.getStatusLine().getStatusCode() == 200) {
      String minitorJson = EntityUtils.toString(httpResponse.getEntity());
      Object response = gson.fromJson(minitorJson, new TypeToken<Object>() {}.getType());
      return response;
    }
  } catch (Exception e) {
    throw e;
  }
  return null;
}
 
Example 3
Source File: WebHttpUtils.java    From frpMgr with MIT License 6 votes vote down vote up
public static String postJson(String url, String json) {
    String data = null;
    logger.debug(">>>请求地址:{},参数:{}", url, json);
    try {
        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(json, ENCODE);
        entity.setContentEncoding(ENCODE);
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity httpEntity = response.getEntity();
                data = EntityUtils.toString(httpEntity, ENCODE);
                logger.debug(">>>返回结果:{}", data);
                EntityUtils.consume(httpEntity);
            } else {
                httpPost.abort();
            }
        }
    } catch (Exception e) {
        logger.error(">>>请求异常", e);
    }
    return data;
}
 
Example 4
Source File: HttpUtil.java    From flink-learning with Apache License 2.0 6 votes vote down vote up
/**
     * 发送 POST 请求(HTTP),JSON形式
     *
     * @param url        调用的地址
     * @param jsonParams 调用的参数
     * @return
     * @throws Exception
     */
    public static CloseableHttpResponse doPostResponse(String url, String jsonParams) throws Exception {
        CloseableHttpResponse response = null;
        HttpPost httpPost = new HttpPost(url);

        try {
            StringEntity entity = new StringEntity(jsonParams, "UTF-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");

            httpPost.setEntity(entity);
            httpPost.setHeader("content-type", "application/json");
            //如果要设置 Basic Auth 的话
//        httpPost.setHeader("Authorization", getHeader());
            response = httpClient.execute(httpPost);
        } finally {
            if (response != null) {
                EntityUtils.consume(response.getEntity());
            }
        }
        return response;
    }
 
Example 5
Source File: HttpMethed.java    From gsc-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * constructor.
 */
public static HttpResponse createConnect1(String url, JSONObject requestBody) {
    try {
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                connectionTimeout);
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                connectionTimeout * 10000);
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout * 10000);
        httppost = new HttpPost(url);
        httppost.setHeader("Content-type", "application/json; charset=utf-8");
        httppost.setHeader("Connection", "Close");
        if (requestBody != null) {
            StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8"));
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httppost.setEntity(entity);
        }
        response = httpClient.execute(httppost);
    } catch (Exception e) {
        e.printStackTrace();
        httppost.releaseConnection();
        return null;
    }
    return response;
}
 
Example 6
Source File: HttpMethed.java    From gsc-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * constructor.
 */
public static HttpResponse createConnect(String url, JsonObject requestBody) {
    try {
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                connectionTimeout);
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
        httppost = new HttpPost(url);
        httppost.setHeader("Content-type", "application/json; charset=utf-8");
        httppost.setHeader("Connection", "Close");
        if (requestBody != null) {
            StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8"));
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httppost.setEntity(entity);
        }
        response = httpClient.execute(httppost);
    } catch (Exception e) {
        e.printStackTrace();
        httppost.releaseConnection();
        return null;
    }
    return response;
}
 
Example 7
Source File: HttpUtils.java    From DataLink with Apache License 2.0 6 votes vote down vote up
/**
 * 发送 POST 请求(HTTP、HTTPS都支持)— 支持传入header
 *
 * @param json 请求体
 * @param headerMap 请求头
 * @return json
 */
public static String doPost(String url, String json, Map<String, String> headerMap) {
    HttpPost httpPost = new HttpPost(url);
    StringEntity stringEntity = new StringEntity(json, CHARSET);// 解决中文乱码问题
    stringEntity.setContentEncoding(CHARSET);
    stringEntity.setContentType("application/json");
    httpPost.setEntity(stringEntity);
    if(headerMap != null && headerMap.size() > 0){
        Iterator<Map.Entry<String, String>> iterator = headerMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, String> entry =  iterator.next();
            httpPost.setHeader(entry.getKey(),entry.getValue());
        }
    }
    return doRequest(url,httpPost);
}
 
Example 8
Source File: HttpUtil.java    From roncoo-education with MIT License 6 votes vote down vote up
/**
 * 
 * @param url
 * @param param
 * @return
 */
public static String post(String url, Map<String, Object> param) {
	logger.info("POST 请求, url={},map={}", url, param.toString());
	try {
		HttpPost httpPost = new HttpPost(url.trim());
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT).setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();
		httpPost.setConfig(requestConfig);
		httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
		StringEntity se = new StringEntity(param.toString(), CHARSET_UTF_8);
		se.setContentType(CONTENT_TYPE_TEXT_JSON);
		se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
		httpPost.setEntity(se);
		HttpResponse httpResponse = HttpClientBuilder.create().build().execute(httpPost);
		return EntityUtils.toString(httpResponse.getEntity(), CHARSET_UTF_8);
	} catch (Exception e) {
		logger.info("HTTP请求出错", e);
		e.printStackTrace();
	}
	return "";
}
 
Example 9
Source File: HttpUtil.java    From flink-learning with Apache License 2.0 6 votes vote down vote up
/**
     * 发送 POST 请求(HTTP),JSON形式
     *
     * @param url        调用的地址
     * @param jsonParams 调用的参数
     * @return
     * @throws Exception
     */
    public static CloseableHttpResponse doPostResponse(String url, String jsonParams) throws Exception {
        CloseableHttpResponse response = null;
        HttpPost httpPost = new HttpPost(url);

        try {
            StringEntity entity = new StringEntity(jsonParams, "UTF-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");

            httpPost.setEntity(entity);
            httpPost.setHeader("content-type", "application/json");
            //如果要设置 Basic Auth 的话
//        httpPost.setHeader("Authorization", getHeader());
            response = httpClient.execute(httpPost);
        } finally {
            if (response != null) {
                EntityUtils.consume(response.getEntity());
            }
        }
        return response;
    }
 
Example 10
Source File: HttpUtil.java    From flink-learning with Apache License 2.0 6 votes vote down vote up
public static String doPostString(String url, String jsonParams) throws Exception {
        CloseableHttpResponse response = null;
        HttpPost httpPost = new HttpPost(url);

        String httpStr;
        try {
            StringEntity entity = new StringEntity(jsonParams, "UTF-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");

            httpPost.setEntity(entity);
            httpPost.setHeader("content-type", "application/json");
            //如果要设置 Basic Auth 的话
//        httpPost.setHeader("Authorization", getHeader());
            response = httpClient.execute(httpPost);
            httpStr = EntityUtils.toString(response.getEntity(), "UTF-8");

        } finally {
            if (response != null) {
                EntityUtils.consume(response.getEntity());
                response.close();
            }
        }
        return httpStr;
    }
 
Example 11
Source File: HttpUtils.java    From DataLink with Apache License 2.0 5 votes vote down vote up
/**
 * 发送 POST 请求(HTTP、HTTPS都支持)— 不支持传入header
 *
 * @param json
 * @return json
 */
public static String doPost(String url, String json) {
    HttpPost httpPost = new HttpPost(url);
    StringEntity stringEntity = new StringEntity(json, CHARSET);// 解决中文乱码问题
    stringEntity.setContentEncoding(CHARSET);
    stringEntity.setContentType("application/json");
    httpPost.setEntity(stringEntity);
    return doRequest(url,httpPost);
}
 
Example 12
Source File: HttpClientUtils.java    From wechat-core with Apache License 2.0 5 votes vote down vote up
private static void buildPostParam(HttpPost postReq, String postJsonParam, Charset charset) {
    if (StringUtils.isEmpty(postJsonParam)) {
        return;
    }
    StringEntity entity = new StringEntity(postJsonParam, charset);
    entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
    entity.setContentEncoding(charset.displayName());
    postReq.setEntity(entity);
}
 
Example 13
Source File: HttpClientPool.java    From FATE-Serving with Apache License 2.0 5 votes vote down vote up
public static String sendPost(String url, Map<String, Object> requestData, Map<String, String> headers) {
    HttpPost httpPost = new HttpPost(url);
    config(httpPost, headers);
    StringEntity stringEntity = new StringEntity(ObjectTransform.bean2Json(requestData), Dict.CHARSET_UTF8);
    stringEntity.setContentEncoding(Dict.CHARSET_UTF8);
    httpPost.setEntity(stringEntity);
    return getResponse(httpPost);
}
 
Example 14
Source File: HttpUtils.java    From lorne_core with Apache License 2.0 5 votes vote down vote up
/**
 * http post string请求
 *
 * @param url  请求地址
 * @param data 请求数据
 * @param type 请求数据格式
 * @return  result 相应结果
 */
public static String postString(String url, String data, String type) {
    CloseableHttpClient httpClient = HttpClientFactory.createHttpClient();
    HttpPost request = new HttpPost(url);
    StringEntity stringEntity = new StringEntity(data, "UTF-8");
    stringEntity.setContentEncoding("UTF-8");
    stringEntity.setContentType(type);
    request.setEntity(stringEntity);
    return execute(httpClient, request);
}
 
Example 15
Source File: HttpServerUtilities.java    From Repeat with Apache License 2.0 5 votes vote down vote up
private static Void prepareStringResponse(HttpAsyncExchange exchange, int code, String data, String contentType) throws IOException {
	HttpResponse response = exchange.getResponse();
	response.setStatusCode(code);
	StringEntity entity = new StringEntity(data);
	entity.setContentEncoding("UTF-8");
	entity.setContentType(contentType);
	response.setEntity(entity);
	exchange.submitResponse(new BasicAsyncResponseProducer(response));

	if (code != 200) {
		LOGGER.warning("HTTP response with code " + code + ": " + data);
	}
       return null;
}
 
Example 16
Source File: HttpClientUtils.java    From JobX with Apache License 2.0 5 votes vote down vote up
public static String httpPostRequest(String url, String params) throws UnsupportedEncodingException {
    HttpPost httpPost = new HttpPost(url);

    StringEntity entitystring = new StringEntity(params, "utf-8");//解决中文乱码问题

    entitystring.setContentEncoding("UTF-8");
    entitystring.setContentType("application/json");
    httpPost.setEntity(entitystring);

    return getResult(httpPost);
}
 
Example 17
Source File: HerokuDeployApi.java    From heroku-maven-plugin with MIT License 5 votes vote down vote up
public BuildInfo createBuild(String appName, URI sourceBlob, String sourceBlobVersion, List<String> buildpacks) throws IOException, HerokuDeployApiException {
    // Create API payload
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode root = mapper.createObjectNode();

    ObjectNode sourceBlobObject = root.putObject("source_blob");
    sourceBlobObject.put("url", sourceBlob.toString());
    sourceBlobObject.put("version", sourceBlobVersion);

    ArrayNode buildpacksArray = root.putArray("buildpacks");
    buildpacks.forEach(buildpackString -> {
        ObjectNode buildpackObjectNode = buildpacksArray.addObject();

        if (buildpackString.startsWith("http")) {
            buildpackObjectNode.put("url", buildpackString);
        } else {
            buildpackObjectNode.put("name", buildpackString);
        }
    });

    StringEntity apiPayloadEntity = new StringEntity(root.toString());
    apiPayloadEntity.setContentType("application/json");
    apiPayloadEntity.setContentEncoding("UTF-8");

    // Send request
    CloseableHttpClient client = HttpClients.createSystem();

    HttpPost request = new HttpPost("https://api.heroku.com/apps/" + appName + "/builds");
    httpHeaders.forEach(request::setHeader);
    request.setEntity(apiPayloadEntity);

    CloseableHttpResponse response = client.execute(request);

    return handleBuildInfoResponse(appName, mapper, response);
}
 
Example 18
Source File: RpcHttpClient.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
public <T> T doPost(String url, String jsonBody, Class<T> tClass) throws Throwable {
    long start = System.currentTimeMillis();
    CloseableHttpClient httpClient = getCloseableHttpClient();
    CloseableHttpResponse response = null;
    try {
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = parseRequestConfig();
        httpPost.setConfig(requestConfig);

        StringEntity requestEntity = new StringEntity(jsonBody, "utf-8");
        requestEntity.setContentEncoding("UTF-8");
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setEntity(requestEntity);

        response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("http client post success. url: {}. latency: {}ms.", url, System.currentTimeMillis() -
                start);
        }
        return JSON.parseObject(EntityUtils.toString(entity), tClass);
    } catch (Throwable throwable) {
        LOGGER.error(
            "http client post error. url: " + url + ", body: " + jsonBody + ". latency: " +
                (System.currentTimeMillis() - start)
                + "ms.", throwable);
        throw throwable;
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                LOGGER.error("http client post close response error.", e);
            }
        }
    }
}
 
Example 19
Source File: HttpClientUtils.java    From frpMgr with MIT License 5 votes vote down vote up
/**
	 * http的post请求,增加异步请求头参数,传递json格式参数
	 */
	public static String ajaxPostJson(String url, String jsonString, String charset) {
		HttpPost httpPost = new HttpPost(url);
		httpPost.setHeader("X-Requested-With", "XMLHttpRequest");
//		try {
			StringEntity stringEntity = new StringEntity(jsonString, charset);// 解决中文乱码问题
			stringEntity.setContentEncoding(charset);
			stringEntity.setContentType("application/json");
			httpPost.setEntity(stringEntity);
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		}
		return executeRequest(httpPost, charset);
	}
 
Example 20
Source File: SparkJobServerClientImpl.java    From SparkJobServerClient with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public SparkJobResult startJob(String data, Map<String, String> params) throws SparkJobServerClientException {
	final CloseableHttpClient httpClient = buildClient();
	try {
		if (params == null || params.isEmpty()) {
			throw new SparkJobServerClientException("The given params is null or empty.");
		}
		if (params.containsKey(ISparkJobServerClientConstants.PARAM_APP_NAME) &&
		    params.containsKey(ISparkJobServerClientConstants.PARAM_CLASS_PATH)) {
			StringBuffer postUrlBuff = new StringBuffer(jobServerUrl);
			postUrlBuff.append("jobs?");
			int num = params.size();
			for (String key : params.keySet()) {
				postUrlBuff.append(key).append('=').append(params.get(key));
				num--;
				if (num > 0) {
					postUrlBuff.append('&');
				}
			}
			HttpPost postMethod = new HttpPost(postUrlBuff.toString());
			postMethod.setConfig(getRequestConfig());
               setAuthorization(postMethod);
               if (data != null) {
				StringEntity strEntity = new StringEntity(data);
				strEntity.setContentEncoding("UTF-8");
				strEntity.setContentType("text/plain");
				postMethod.setEntity(strEntity);
			}
			
			HttpResponse response = httpClient.execute(postMethod);
			String resContent = getResponseContent(response.getEntity());
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_ACCEPTED) {
				return parseResult(resContent);
			} else {
				logError(statusCode, resContent, true);
			}
		} else {
			throw new SparkJobServerClientException("The given params should contains appName and classPath");
		}
	} catch (Exception e) {
		processException("Error occurs when trying to start a new job:", e);
	} finally {
		close(httpClient);
	}
	return null;
}