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

The following examples show how to use org.apache.http.entity.StringEntity#setContentType() . 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: 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 2
Source File: AzkabanAjaxAPIClient.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
private static HttpPost preparePostRequest(String requestUrl, String sessionId, Map<String, String> params)
    throws IOException {
  // Create post request
  HttpPost postRequest = new HttpPost(requestUrl);
  StringBuilder stringEntityBuilder = new StringBuilder();
  stringEntityBuilder.append(String.format("session.id=%s", sessionId));
  for (Map.Entry<String, String> entry : params.entrySet()) {
    if (stringEntityBuilder.length() > 0) {
      stringEntityBuilder.append("&");
    }
    stringEntityBuilder.append(String.format("%s=%s", entry.getKey(), entry.getValue()));
  }
  StringEntity input = new StringEntity(stringEntityBuilder.toString());
  input.setContentType("application/x-www-form-urlencoded");
  postRequest.setEntity(input);
  postRequest.setHeader("X-Requested-With", "XMLHttpRequest");

  return postRequest;
}
 
Example 3
Source File: AbstractRestFuncTestCase.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
private String getSession(String schedulerUrl, String username, String password) throws Exception {
    String resourceUrl = getResourceUrl("login");
    HttpPost httpPost = new HttpPost(resourceUrl);
    StringBuilder buffer = new StringBuilder();
    buffer.append("username=").append(username).append("&password=").append(password);
    StringEntity entity = new StringEntity(buffer.toString());
    entity.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    httpPost.setEntity(entity);
    HttpResponse response = new HttpClientBuilder().insecure(true).useSystemProperties().build().execute(httpPost);
    String responseContent = EntityUtils.toString(response.getEntity());
    if (STATUS_OK != getStatusCode(response)) {
        throw new RuntimeException(String.format("Authentication error: %n%s", responseContent));
    } else {
        return responseContent;
    }
}
 
Example 4
Source File: HttpUtil.java    From common-project with Apache License 2.0 6 votes vote down vote up
public static String sendJSONPost(String url, String jsonData, Map<String, String> headers) {
    String result = null;
    HttpPost httpPost = new HttpPost(url);
    StringEntity postEntity = new StringEntity(jsonData, CHARSET_NAME);
    postEntity.setContentType("application/json");
    httpPost.setEntity(postEntity);
    httpPost.setHeader("Content-Type", "application/json");
    HttpClient client = HttpClients.createDefault();
    if (headers != null && !headers.isEmpty()) {
        headers.forEach((k, v) -> {
            httpPost.setHeader(k, v);
        });
    }
    try {
        HttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity, "UTF-8");
    } catch (Exception e) {
        logger.error("http request error ", e);
    } finally {
        httpPost.abort();
    }
    return result;
}
 
Example 5
Source File: HttpCallOtherInterfaceUtils.java    From sophia_scaffolding with Apache License 2.0 6 votes vote down vote up
public static String callOtherPostInterface(JSONObject jsonParam, String gatewayUrl, String postUrl) {
    HttpClient client = HttpClients.createDefault();
    // 要调用的接口方法
    String url = gatewayUrl + postUrl;
    HttpPost post = new HttpPost(url);
    JSONObject jsonObject = null;
    try {
        StringEntity s = new StringEntity(jsonParam.toString(), "UTF-8");
        //s.setContentEncoding("UTF-8");//此处测试发现不能单独设置字符串实体的编码,否则出错!应该在创建对象时创建
        s.setContentType("application/json");
        post.setEntity(s);
        post.addHeader("content-type", "application/json;charset=UTF-8");
        HttpResponse res = client.execute(post);
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // 返回json格式:
            jsonObject = JSONObject.parseObject(EntityUtils.toString(res.getEntity()));
        }
    } catch (Exception e) {
        System.out.println("服务间接口调用出错!");
        e.printStackTrace();
        //throw new RuntimeException(e);
    }
    return null == jsonObject?"":jsonObject.toString();
}
 
Example 6
Source File: RestClient.java    From product-private-paas with Apache License 2.0 6 votes vote down vote up
public HttpResponse doPut(URI resourcePath, String jsonParamString) throws Exception {

        HttpPut putRequest = null;
        try {
            putRequest = new HttpPut(resourcePath);

            StringEntity input = new StringEntity(jsonParamString);
            input.setContentType("application/json");
            putRequest.setEntity(input);
            String userPass = getUsernamePassword();
            String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userPass.getBytes("UTF-8"));
            putRequest.addHeader("Authorization", basicAuth);
            return httpClient.execute(putRequest, new HttpResponseHandler());
        } finally {
            releaseConnection(putRequest);
        }
    }
 
Example 7
Source File: TestHTTPSource.java    From mt-flume with Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleEvent() throws Exception {
  StringEntity input = new StringEntity("[{\"headers\" : {\"a\": \"b\"},\"body\":"
          + " \"random_body\"}]");
  input.setContentType("application/json");
  postRequest.setEntity(input);

  httpClient.execute(postRequest);
  Transaction tx = channel.getTransaction();
  tx.begin();
  Event e = channel.take();
  Assert.assertNotNull(e);
  Assert.assertEquals("b", e.getHeaders().get("a"));
  Assert.assertEquals("random_body", new String(e.getBody(),"UTF-8"));
  tx.commit();
  tx.close();
}
 
Example 8
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 9
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 10
Source File: ApacheHttpUtils.java    From karate with MIT License 5 votes vote down vote up
public static HttpEntity getEntity(String value, String mediaType, Charset charset) {
    try {
        ContentType ct = getContentType(mediaType, charset);
        if (ct == null) { // "bad" value such as an empty string
            StringEntity entity = new StringEntity(value);
            entity.setContentType(mediaType);
            return entity;
        } else {
            return new StringEntity(value, ct);
        }            
    } catch (Exception e) {
        throw new RuntimeException(e);
    }         
}
 
Example 11
Source File: ResponseAttachmentTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private HttpPost getHttpPost(URL url) throws URISyntaxException, UnsupportedEncodingException {
    // For POST we are using the custom op instead read-attribute that we use for GET
    // but this is just a convenient way to exercise the op (GET can't call custom ops),
    // and isn't some limitation of POST
    ModelNode cmd = Util.createEmptyOperation(LogStreamExtension.STREAM_LOG_FILE, PathAddress.pathAddress(SUBSYSTEM, LogStreamExtension.SUBSYSTEM_NAME));
    String cmdStr = cmd.toJSONString(true);
    HttpPost post = new HttpPost(url.toURI());
    StringEntity entity = new StringEntity(cmdStr);
    entity.setContentType(APPLICATION_JSON);
    post.setEntity(entity);

    return post;
}
 
Example 12
Source File: JerseyApiLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenAddEmployee_whenJsonRequestSent_thenResponseCodeCreated() throws IOException {
    final HttpPost request = new HttpPost(SERVICE_URL);

    Employee emp = new Employee(5, "Johny");
    ObjectMapper mapper = new ObjectMapper();
    String empJson = mapper.writeValueAsString(emp);
    StringEntity input = new StringEntity(empJson);
    input.setContentType("application/json");
    request.setEntity(input);
    final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);

    assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpStatus.SC_CREATED);
}
 
Example 13
Source File: CustomTaskImpl.java    From product-ei with Apache License 2.0 5 votes vote down vote up
@Override
public void execute() {

    try (DefaultHttpClient httpClient = new DefaultHttpClient()) {

        //prepare the request
        HttpPost postRequest = new HttpPost(url);
        StringEntity input = new StringEntity(message);
        input.setContentType(HttpConstants.MEDIA_TYPE_APPLICATION_JSON);
        postRequest.setEntity(input);

        //Invoke post request and receive response
        HttpResponse response = httpClient.execute(postRequest);
        if (response.getStatusLine().getStatusCode() != 200) {
            LOG.error(
                    "Error invoking incrementing the invocation count. Unexpected response received: " + response);
        }

        //build response string
        String responseAsString = "";
        if (response.getEntity() != null) {
            InputStream in = response.getEntity().getContent();
            int length;
            byte[] tmp = new byte[2048];
            StringBuilder buffer = new StringBuilder();
            while ((length = in.read(tmp)) != -1) {
                buffer.append(new String(tmp, 0, length));
            }
            responseAsString = buffer.toString();
        }

        //extract number of invocations
        JSONObject responseJson = new JSONObject(responseAsString);
        int receivedInvocationCount = responseJson.getInt("invocationCount");
        LOG.info("number of invocations for " + uuid + "=" + receivedInvocationCount);
    } catch (IOException e) {
        LOG.error("Error incrementing the invocation count. Unexpected response received: ", e);
    }
}
 
Example 14
Source File: PostsModel.java    From buddycloud-android with Apache License 2.0 5 votes vote down vote up
private void savePendingPost(final Context context, final String channelJid,
		final JSONObject post, final Semaphore semaphore) {
	try {
		JSONObject tempPost = new JSONObject(post, new String[] {"content", "replyTo", "media" });
		StringEntity requestEntity = new StringEntity(tempPost.toString(), "UTF-8");
		requestEntity.setContentType("application/json");

		BuddycloudHTTPHelper.post(postsUrl(context, channelJid), true, false, requestEntity, context,
			new ModelCallback<JSONObject>() {
				@Override
				public void success(JSONObject response) {
					String postId = post.optString("id");
					PostsDAO.getInstance(context).delete(channelJid, postId);
					notifyDeleted(channelJid, postId, post.optString("replyTo", null));
					notifyChanged();
					semaphore.release();
				}

				@Override
				public void error(Throwable throwable) {
					semaphore.release();
				}
			});
	} catch (Exception e) {
		semaphore.release();
	}
}
 
Example 15
Source File: QpidRestAPIQueueCreator.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private void managementCreateQueue(final String name, final HttpClientContext context)
{
    HttpPut put = new HttpPut(String.format(_queueApiUrl, _virtualhostnode, _virtualhost, name));

    StringEntity input = new StringEntity("{}", StandardCharsets.UTF_8);
    input.setContentType("application/json");
    put.setEntity(input);

    executeManagement(put, context);
}
 
Example 16
Source File: WechatUtil.java    From anyline with Apache License 2.0 4 votes vote down vote up
/**
 * 发送裂变红包
 * @param pack  pack
 * @param config  config
 * @return return
 */
public static WechatFissionRedpackResult sendRedpack(WechatConfig config, WechatFissionRedpack pack){
	WechatFissionRedpackResult result = new WechatFissionRedpackResult();
	pack.setNonce_str(BasicUtil.getRandomLowerString(20));
	if(BasicUtil.isEmpty(pack.getWxappid())){
		pack.setWxappid(config.APP_ID);
	}
	if(BasicUtil.isEmpty(pack.getMch_id())){
		pack.setMch_id(config.PAY_MCH_ID);
	}
	if(BasicUtil.isEmpty(pack.getMch_billno())){
		pack.setMch_billno(BasicUtil.getRandomLowerString(20));
	}
	Map<String, Object> map = BeanUtil.toMap(pack);
	String sign = WechatUtil.sign(config.PAY_API_SECRET,map);

	map.put("sign", sign);

	if(ConfigTable.isDebug() && log.isWarnEnabled()){
		log.warn("[发送裂变红包][sign:{}]", sign);
	}
	String xml = BeanUtil.map2xml(map);
	if(ConfigTable.isDebug() && log.isWarnEnabled()){
		log.warn("[发送裂变红包][xml:{}]", xml);
		log.warn("[发送裂变红包][证书:{}]", config.PAY_KEY_STORE_FILE);
	}

	File keyStoreFile = new File(config.PAY_KEY_STORE_FILE);
	if(!keyStoreFile.exists()){
		log.warn("[密钥文件不存在][file:{}]", config.PAY_KEY_STORE_FILE);
		return new WechatFissionRedpackResult(false,"密钥文件不存在");
	}
	String keyStorePassword = config.PAY_KEY_STORE_PASSWORD;
	if(BasicUtil.isEmpty(keyStorePassword)){
		log.warn("未设置密钥文件密码");
		return new WechatFissionRedpackResult(false,"未设置密钥文件密码");
	}
	try{
		CloseableHttpClient httpclient = HttpUtil.ceateSSLClient(keyStoreFile, HttpUtil.PROTOCOL_TLSV1, keyStorePassword);
		StringEntity  reqEntity  = new StringEntity(xml,"UTF-8");
		reqEntity.setContentType("application/x-www-form-urlencoded");
		String txt = HttpUtil.post(httpclient, WechatConfig.API_URL_SEND_GROUP_REDPACK, "UTF-8", reqEntity).getText();
		if(ConfigTable.isDebug() && log.isWarnEnabled()){
			log.warn("[发送裂变红包调用][result:{}]", txt);
		}
		result = BeanUtil.xml2object(txt, WechatFissionRedpackResult.class);
	}catch(Exception e){
		e.printStackTrace();
		return new WechatFissionRedpackResult(false,e.getMessage());
	}
	return result;
}
 
Example 17
Source File: Communicator.java    From AIDR with GNU Affero General Public License v3.0 4 votes vote down vote up
public int sendPut(String data, String url) {
    int responseCode = -1;
    HttpClient httpClient = new DefaultHttpClient();
    try {

        HttpPut request = new HttpPut(url);
        StringEntity params =new StringEntity(data,"UTF-8");
        params.setContentType("application/json");
        request.addHeader("content-type", "application/json");
        request.addHeader("Accept", "*/*");
        request.addHeader("Accept-Encoding", "gzip,deflate,sdch");
        request.addHeader("Accept-Language", "en-US,en;q=0.8");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);
        responseCode = response.getStatusLine().getStatusCode();
        if (response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 204) {

            BufferedReader br = new BufferedReader(
                    new InputStreamReader((response.getEntity().getContent())));

            String output;
            // System.out.println("Output from Server ...." + response.getStatusLine().getStatusCode() + "\n");
            while ((output = br.readLine()) != null) {
                // System.out.println(output);
            }
        }
        else{
        	logger.error("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        }

    }catch (Exception ex) {
        logger.warn("Error in processing request for data : " + data + " and url : " + url,ex);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    return responseCode;

}
 
Example 18
Source File: JIRAConnectorImpl.java    From xframium-java with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean changeExecutionStatus(String testCycleID, String issueKey, ExecutionStatus status, String comment)
		throws Exception {

	JIRAExecution execution = new JIRAExecution();
	execution.setCycleId(testCycleID);
	execution.setIssueKey(issueKey);
	execution.setStatus(status);
	
	StringBuilder commentBuilder = new StringBuilder();
	for(String commentPart: comment.split("\r\n")){
		commentBuilder.append(commentPart.trim()).append(",");
	}
	comment = commentBuilder.toString().substring(0,700);
	
	execution.setComment(comment);

	String executionId = getExecutionId(execution.getCycleId(), execution.getIssueKey());

	if (executionId == null)
		return false;

	execution.setId(executionId);

	String updateExecutionURL = serverUrl.concat(UPD_EXECUTION_URL).replace("{executionId}", execution.getId());

	HttpPut putRequest = JIRAConnectorUtil.getHttpPutRequest(updateExecutionURL, credentials);

	String payload = EXECUTION_PAYLOAD_JSON.replace("{status}", String.valueOf(execution.getStatus().getValue()))
			.replace("{comment}", String.valueOf(execution.getComment()));

	StringEntity content = new StringEntity(payload);
	content.setContentType(JSON_CONTENT_TYPE);
	putRequest.setEntity(content);

	HttpClient client = JIRAConnector.getHttpClient(updateExecutionURL, useProxy, proxyHost);

	HttpResponse response = client.execute(putRequest);

	if (response.getStatusLine().getStatusCode() == STATUS_OK) {
		return true;
	}

	return false;
}
 
Example 19
Source File: SxmpSender.java    From cloudhopper-commons with Apache License 2.0 4 votes vote down vote up
static public Response send(String url, Request request, boolean shouldParseResponse) throws UnsupportedEncodingException, SxmpErrorException, IOException, SxmpParsingException, SAXException, ParserConfigurationException {
    // convert request into xml
    String requestXml = SxmpWriter.createString(request);
    String responseXml = null;

    HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    client.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

    long start = System.currentTimeMillis();
    long stop = 0;

    logger.debug("Request XML:\n" + requestXml);

    // execute request
    try {
        HttpPost post = new HttpPost(url);
        StringEntity entity = new StringEntity(requestXml);
        // write old or new encoding?
        if (request.getVersion().equals(SxmpParser.VERSION_1_1)) {
            // v1.1 is utf-8
            entity.setContentType("text/xml; charset=\"utf-8\"");
        } else {
            // v1.0 was 8859-1, though that's technically wrong
            // unspecified XML must be encoded in UTF-8
            // maintained this way for backward compatibility
            entity.setContentType("text/xml; charset=\"iso-8859-1\"");
        }
        post.setEntity(entity);

        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        // execute request (will throw exception if fails)
        responseXml = client.execute(post, responseHandler);

        stop = System.currentTimeMillis();
    } finally {
        // clean up all resources
        client.getConnectionManager().shutdown();
    }

    logger.debug("Response XML:\n" + responseXml);
    logger.debug("Response Time: " + (stop - start) + " ms");

    // deliver responses sometimes aren't parseable since its acceptable
    // for delivery responses to merely return "OK" and an HTTP 200 error
    if (!shouldParseResponse) {
        return null;
    } else {
        // convert response xml into an object
        SxmpParser parser = new SxmpParser(SxmpParser.VERSION_1_0);
        // v1.0 data remains in ISO-8859-1, and responses are v1.0
        ByteArrayInputStream bais = new ByteArrayInputStream(responseXml.getBytes("ISO-8859-1"));
        Operation op = parser.parse(bais);

        if (!(op instanceof Response)) {
            throw new SxmpErrorException(SxmpErrorCode.OPTYPE_MISMATCH, "Unexpected response class type parsed");
        }

        return (Response)op;
    }
}
 
Example 20
Source File: Remote.java    From HongsCORE with MIT License 3 votes vote down vote up
/**
 * 构建JSON实体
 *
 * 讲数据处理成JSON格式,
 * Content-Type: application/json; charset=utf-8
 *
 * @param data
 * @return
 * @throws HongsException
 */
public static HttpEntity buildJson(Map<String, Object> data)
        throws HongsException {
    StringEntity enti = new StringEntity(Dawn.toString(data), "UTF-8");
                 enti.setContentType/**/("application/json");
                 enti.setContentEncoding("UTF-8");
    return enti;
}