当前位置: 首页>>代码示例>>Java>>正文


Java HttpPost.setEntity方法代码示例

本文整理汇总了Java中org.apache.http.client.methods.HttpPost.setEntity方法的典型用法代码示例。如果您正苦于以下问题:Java HttpPost.setEntity方法的具体用法?Java HttpPost.setEntity怎么用?Java HttpPost.setEntity使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.apache.http.client.methods.HttpPost的用法示例。


在下文中一共展示了HttpPost.setEntity方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: create

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
/**
 * Realiza a emissão do boleto bancário para o cliente informado
 * @param boletoRecebimento: boleto à ser emitido
 * @return BoletoRecebimento
 */
public BoletoRecebimento create(BoletoRecebimento boletoRecebimento) throws IOException, PJBankException {
    PJBankClient client = new PJBankClient(this.endPoint.concat("/transacoes"));
    HttpPost httpPost = client.getHttpPostClient();
    DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");

    JSONObject params = new JSONObject();

    params.put("vencimento", dateFormat.format(boletoRecebimento.getVencimento()));
    params.put("valor", boletoRecebimento.getValor());
    params.put("juros", boletoRecebimento.getJuros());
    params.put("multa", boletoRecebimento.getMulta());
    params.put("desconto", boletoRecebimento.getDesconto());
    params.put("nome_cliente", boletoRecebimento.getCliente().getNome());
    params.put("cpf_cliente", boletoRecebimento.getCliente().getCpfCnpj());
    params.put("endereco_cliente", boletoRecebimento.getCliente().getEndereco().getLogradouro());
    params.put("numero_cliente", boletoRecebimento.getCliente().getEndereco().getNumero());
    params.put("complemento_cliente", boletoRecebimento.getCliente().getEndereco().getComplemento());
    params.put("bairro_cliente", boletoRecebimento.getCliente().getEndereco().getBairro());
    params.put("cidade_cliente", boletoRecebimento.getCliente().getEndereco().getCidade());
    params.put("estado_cliente", boletoRecebimento.getCliente().getEndereco().getEstado());
    params.put("cep_cliente", boletoRecebimento.getCliente().getEndereco().getCep());
    params.put("logo_url", boletoRecebimento.getLogoUrl());
    params.put("texto", boletoRecebimento.getTexto());
    params.put("grupo", boletoRecebimento.getGrupo());
    params.put("pedido_numero", boletoRecebimento.getPedidoNumero());

    httpPost.setEntity(new StringEntity(params.toString(), StandardCharsets.UTF_8));

    String response = EntityUtils.toString(client.doRequest(httpPost).getEntity());

    JSONObject responseObject = new JSONObject(response);
    boletoRecebimento.setIdUnico(responseObject.getString("nossonumero"));
    boletoRecebimento.setLinkBoleto(responseObject.getString("linkBoleto"));
    boletoRecebimento.setLinkGrupo(responseObject.getString("linkGrupo"));
    boletoRecebimento.setLinhaDigitavel(responseObject.getString("linhaDigitavel"));

    return boletoRecebimento;
}
 
开发者ID:pjbank,项目名称:pjbank-java-sdk,代码行数:44,代码来源:BoletosManager.java

示例2: postJson

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
public static String postJson(String url, String json, String authorization) {
    CloseableHttpClient httpClient = HttpClientFactory.createHttpClient();
    HttpPost request = new HttpPost(url);
    StringEntity stringEntity = new StringEntity(json, "utf-8");
    request.addHeader("Authorization",authorization);
    request.addHeader("Accept","application/json");
    request.addHeader("Content-Type","application/json;charset=utf-8");
    request.setEntity(stringEntity);
    return com.lorne.core.framework.utils.http.HttpUtils.execute(httpClient, request);
}
 
开发者ID:1991wangliang,项目名称:yuntongxun-restapi,代码行数:11,代码来源:HttpUtils.java

示例3: selectAvgByDeviceAndSensor

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
@Override
public Status selectAvgByDeviceAndSensor(String deviceCode, String sensorCode, Date startTime, Date endTime) {
	HttpClient hc = getHttpClient();
	HttpPost post = new HttpPost(QUERY_URL);
	HttpResponse response = null;
	long costTime = 0L;
	try {
		List<NameValuePair> nameValues = new ArrayList<NameValuePair>();
		String selectSql = "SELECT MEAN(value) FROM sensor where device_code='" + deviceCode + "' and sensor_code='"
				+ sensorCode + "' and time>=" + TimeUnit.MILLISECONDS.toNanos(startTime.getTime()) + " and time<=" + TimeUnit.MILLISECONDS.toNanos(endTime.getTime());
		NameValuePair nameValue = new BasicNameValuePair("q", selectSql);
		//System.out.println(selectSql);
		nameValues.add(nameValue);
		HttpEntity entity = new UrlEncodedFormEntity(nameValues, "utf-8");
		post.setEntity(entity);
		long startTime1 = System.nanoTime();
		response = hc.execute(post);
		long endTime1 = System.nanoTime();
		costTime = endTime1 - startTime1;
		//System.out.println(response);
	} catch (Exception e) {
		e.printStackTrace();
		return Status.FAILED(-1);
	}finally{
		closeResponse(response);
		closeHttpClient(hc);
	}
	//System.out.println("此次查询消耗时间[" + costTime / 1000 + "]s");
	return Status.OK(costTime);
}
 
开发者ID:dbiir,项目名称:ts-benchmark,代码行数:31,代码来源:InfluxDB.java

示例4: post

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
public static HttpPost post(String url, String body) {
    StringEntity entity = new StringEntity(body, StandardCharsets.UTF_8);
    entity.setContentType(ContentType.APPLICATION_JSON.toString());
    HttpPost req = new HttpPost(url);
    req.setEntity(entity);
    return req;
}
 
开发者ID:kamax-io,项目名称:mxisd,代码行数:8,代码来源:RestClientUtils.java

示例5: postString

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
public static String postString(String url, List<NameValuePair> params, Map<String,String> header) throws IOException {
    HttpClient client = HttpClients.createDefault();
    HttpPost http = new HttpPost(url);

    if (header != null) {
        header.forEach((k, v) -> {
            http.addHeader(k, v);
        });
    }

    http.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
    HttpEntity entity = client.execute(http).getEntity();

    return EntityUtils.toString(entity, "utf-8");
}
 
开发者ID:noear,项目名称:JtSQL,代码行数:16,代码来源:HttpUtil.java

示例6: sendSlackImageResponse

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
private void sendSlackImageResponse(ObjectNode json, String s3Key) {
	try {
		ObjectMapper mapper = new ObjectMapper();
		ObjectNode message = mapper.createObjectNode();
		ArrayNode attachments = mapper.createArrayNode();
		ObjectNode attachment = mapper.createObjectNode();

		String emoji = json.get("text").asText();

		if (UrlValidator.getInstance().isValid(emoji)) {
			attachment.put("title_link", emoji);
			emoji = StringUtils.substringAfterLast(emoji, "/");
		}

		String username = json.get("user_name").asText();
		String responseUrl = json.get("response_url").asText();
		String slackChannelId = json.get("channel_id").asText();
		String imageUrl = String.format("https://s3.amazonaws.com/%s/%s", PROPERTIES.getProperty(S3_BUCKET_NAME), s3Key);

		message.put("response_type", "in_channel");
		message.put("channel_id", slackChannelId);
		attachment.put("title", resolveMessage("slackImageResponse", emoji, username));
		attachment.put("fallback", resolveMessage("approximated", emoji));
		attachment.put("image_url", imageUrl);
		attachments.add(attachment);
		message.set("attachments", attachments);

		HttpClient client = HttpClientBuilder.create().build();
		HttpPost slackResponseReq = new HttpPost(responseUrl);
		slackResponseReq.setEntity(new StringEntity(mapper.writeValueAsString(message), ContentType.APPLICATION_JSON));
		HttpResponse slackResponse = client.execute(slackResponseReq);
		int status = slackResponse.getStatusLine().getStatusCode();
		LOG.info("Got {} status from Slack API after sending approximation to response url.", status);
	} catch (UnsupportedOperationException | IOException e) {
		LOG.error("Exception occured when sending Slack response", e);
	}
}
 
开发者ID:villeau,项目名称:pprxmtr,代码行数:38,代码来源:Handler.java

示例7: postInputStreamEntity

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
@Test public void postInputStreamEntity() throws Exception {
  server.enqueue(new MockResponse());

  final HttpPost post = new HttpPost(server.url("/").url().toURI());
  byte[] body = "Hello, world!".getBytes(UTF_8);
  post.setEntity(new InputStreamEntity(new ByteArrayInputStream(body), body.length));
  client.execute(post);

  RecordedRequest request = server.takeRequest();
  assertEquals("Hello, world!", request.getBody().readUtf8());
  assertEquals(request.getHeader("Content-Length"), "13");
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:13,代码来源:OkApacheClientTest.java

示例8: setupBodyContentFormEntity

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
private void setupBodyContentFormEntity(HttpPost httpPost){
    if(isDebug){
        log("Request content: "+mBodyContent);
    }
    StringEntity entity = new StringEntity(mBodyContent,mContentType);
    httpPost.setEntity(entity);
}
 
开发者ID:fcibook,项目名称:QuickHttp,代码行数:8,代码来源:QuickHttpController.java

示例9: report

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
/**
 * 报工
 * 
 */
public boolean report() {
	HttpPost post = new HttpPost(Api.reportUrl);
	try {
		post.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
		HttpResponse resp = client.execute(post);
		JSONObject jo = JSONObject.parseObject(EntityUtils.toString(resp.getEntity()));
		// 报工成功,返回json结构的报文{"data" : [ {},{}...],"success" : true}
		if (jo.getBooleanValue("success")) {
			return true;
		}
		logger.warn(jo.getString("error"));
	} catch (Exception e) {
		logger.error("报工异常:", e);
	}
	return false;
}
 
开发者ID:ichatter,项目名称:dcits-report,代码行数:21,代码来源:UserService.java

示例10: setPostEntity

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
@Override
public void setPostEntity(String xmlstr, HttpPost httppost) throws UnsupportedEncodingException {
    StringEntity input = new StringEntity(xmlstr);
    if (xmlstr != null && !xmlstr.isEmpty()) {
        input.setContentType("application/xml");
    }
    httppost.setEntity(input);
}
 
开发者ID:CognizantQAHub,项目名称:Cognizant-Intelligent-Test-Scripter,代码行数:9,代码来源:QCRestHttpClient.java

示例11: post

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
public HttpClient post(String body) throws UnsupportedEncodingException {
    HttpPost httpPost = new HttpPost(url);
    HttpEntity entity = new StringEntity(body, Charsets.UTF_8);
    httpPost.setEntity(entity);

    httpRequest = httpPost;
    return this;
}
 
开发者ID:FlowCI,项目名称:flow-platform,代码行数:9,代码来源:HttpClient.java

示例12: createChannel

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
private Channel.ChannelData createChannel(String s) throws URISyntaxException, IOException {
    HttpPost req = new HttpPost(url(String.format(CHANNEL_CREATE_URL, this.teams[0].getTeamId())));
    req.addHeader("Content-Type", "application/json");
    req.addHeader("Authorization", "Bearer " + this.token);
    List<String> ids = new ArrayList<>();
    ids.add(this.user.getId());
    ids.add(s);
    Gson jsonReq = new Gson();
    req.setEntity(new StringEntity(jsonReq.toJson(ids)));
    CloseableHttpResponse resp = this.client.execute(req);
    String json = IOUtils.toString(resp.getEntity().getContent(), "UTF-8");
    System.out.println(json);
    return gson.fromJson(json, Channel.ChannelData.class);
}
 
开发者ID:stefandotti,项目名称:intellij-mattermost-plugin,代码行数:15,代码来源:MattermostClient.java

示例13: callGistApi

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
/**
 * Call the API to create gist and return the http url if any
 */
private String callGistApi(String gistJson, GistListener listener) {
    try {
        CloseableHttpClient httpclient = createDefault();
        HttpPost httpPost = new HttpPost(GIST_API);
        httpPost.setHeader("Accept", "application/vnd.github.v3+json");
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(gistJson, ContentType.APPLICATION_JSON));

        CloseableHttpResponse response = httpclient.execute(httpPost);

        HttpEntity responseEntity = response.getEntity();
        JsonObject result = (JsonObject) new JsonParser().parse(EntityUtils.toString(responseEntity));

        EntityUtils.consume(responseEntity);
        response.close();

        httpclient.close();
        return result.getAsJsonPrimitive("html_url").getAsString();
    } catch (Exception ex) {
    }
    return null;
}
 
开发者ID:josesamuel,项目名称:logviewer,代码行数:26,代码来源:GistCreator.java

示例14: sendFormToDLMS

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
/**
 * * Send POST request to DLMS back end with the result file
 * @param bluemixToken - the Bluemix token
 * @param contents - the result file
 * @param jobUrl -  the build url of the build job in Jenkins
 * @param timestamp
 * @return - response/error message from DLMS
 */
public String sendFormToDLMS(String bluemixToken, FilePath contents, String lifecycleStage, String jobUrl, String timestamp) throws IOException {

    // create http client and post method
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost postMethod = new HttpPost(this.dlmsUrl);

    postMethod = addProxyInformation(postMethod);
    // build up multi-part forms
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    if (contents != null) {

        File file = new File(root, contents.getName());
        FileBody fileBody = new FileBody(file);
        builder.addPart("contents", fileBody);


        builder.addTextBody("test_artifact", file.getName());
        if (this.isDeploy) {
            builder.addTextBody("environment_name", environmentName);
        }
        //Todo check the value of lifecycleStage
        builder.addTextBody("lifecycle_stage", lifecycleStage);
        builder.addTextBody("url", jobUrl);
        builder.addTextBody("timestamp", timestamp);

        String fileExt = FilenameUtils.getExtension(contents.getName());
        String contentType;
        switch (fileExt) {
            case "json":
                contentType = CONTENT_TYPE_JSON;
                break;
            case "xml":
                contentType = CONTENT_TYPE_XML;
                break;
            default:
                return "Error: " + contents.getName() + " is an invalid result file type";
        }

        builder.addTextBody("contents_type", contentType);
        HttpEntity entity = builder.build();
        postMethod.setEntity(entity);
        postMethod.setHeader("Authorization", bluemixToken);
    } else {
        return "Error: File is null";
    }


    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(postMethod);
        // parse the response json body to display detailed info
        String resStr = EntityUtils.toString(response.getEntity());
        JsonParser parser = new JsonParser();
        JsonElement element =  parser.parse(resStr);

        if (!element.isJsonObject()) {
            // 401 Forbidden
            return "Error: Upload is Forbidden, please check your org name. Error message: " + element.toString();
        } else {
            JsonObject resJson = element.getAsJsonObject();
            if (resJson != null && resJson.has("status")) {
                return String.valueOf(response.getStatusLine()) + "\n" + resJson.get("status");
            } else {
                // other cases
                return String.valueOf(response.getStatusLine());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}
 
开发者ID:IBM,项目名称:ibm-cloud-devops,代码行数:82,代码来源:PublishTest.java

示例15: doInBackground

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
@Override
protected ArrayList<Integer> doInBackground(Void... params) {
    // TODO: attempt authentication against a network service.
    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);

        //參數
        int length = arraylist.size();
        if (length != 0){
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            String json = new String();
            json+="[";
            for (int i = 0 ; i< length;i++) {
                json += "{\"id\":"+arraylist.get(i).ID+"}";
                if ( i != (length-1) )json +=",";
                else json+="]";
            }
            System.out.println(json);
            parameters.add(new BasicNameValuePair("name", json));
            parameters.add(new BasicNameValuePair("action","update"));
            SharedPreferences sp = getSharedPreferences("now_account", Context.MODE_PRIVATE);
            String stuNum=sp.getString("now_stu_num",null);
            parameters.add(new BasicNameValuePair("FetcherID",stuNum));
            UrlEncodedFormEntity ent = new UrlEncodedFormEntity(parameters, HTTP.UTF_8);
            post.setEntity(ent);
        }

        HttpResponse responsePOST = client.execute(post);

        HttpEntity resEntity = responsePOST.getEntity();


        if (resEntity != null) {
            result = EntityUtils.toString(resEntity);
        }
        JSONArray arr = new JSONArray(result.toString());
        ArrayList<Integer> array = new ArrayList<Integer>();
        for (int i = 0; i < arr.length(); i++) {
            JSONObject lan = arr.getJSONObject(i);
            array.add(lan.getInt("id"));
        }
        return  array;
    } catch (Exception e) {
        // TODO: handle exception
        e.getMessage();
    }
    return null;
}
 
开发者ID:Luodian,项目名称:Shared-Route,代码行数:50,代码来源:ConfirmTaskActivity.java


注:本文中的org.apache.http.client.methods.HttpPost.setEntity方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。