java raw 请求

测试一个接口,在postman里很容易就通过。其中body部分需要上传的参数是这样的

 对应的程序里我是通过创建两个json实现的

import net.sf.json.JSONObject;

    	String sourceBody = new StringBuilder()
				.append("{\"href\":\""+ fromFoundingSource +"\"}")
				.toString();
		
		String destinationBody = new StringBuilder()
				.append("{\"href\":\""+ toFoundingSource +"\"}")
				.toString();
		
		String amountBody = new StringBuilder()
				.append("{\"currency\":\""+ currency +"\",")
				.append("\"value\":\""+ money +"\"}")
				.toString();
		
		JSONObject linksJson = new JSONObject();
		linksJson.put("source", sourceBody);
		linksJson.put("destination", destinationBody);
		
		JSONObject json = new JSONObject();
		json.put("_links", linksJson.toString());
		json.put("amount", amountBody);

 最后将把json作为body参数设置到请求中,完成。

 

Java中发送POST请求并携带"data-raw"数据通常涉及到使用HTTP客户端库,如Apache HttpClient、OkHttp或者最近的Spring框架的RestTemplate。这里我会给出使用`org.apache.httpcomponents.client5`的一个简单示例: ```java import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; public void sendPostRequestWithDataRaw() { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { // 创建POST请求 HttpPost httpPost = new HttpPost("http://example.com/api"); // 添加"data-raw"参数 String rawData = "your_data_here"; List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("data-raw", rawData)); // 设置POST实体,这里我们将其封装为StringEntity HttpEntity entity = new StringEntity(urlencode(params), ContentType.APPLICATION_FORM_URLENCODED); httpPost.setEntity(entity); // 发送请求并获取响应 CloseableHttpResponse response = httpClient.execute(httpPost); try { System.out.println(EntityUtils.toString(response.getEntity())); } finally { response.close(); } } catch (Exception e) { e.printStackTrace(); } } // 这里省略了urlencode方法的实现,实际项目中需要引入合适的库或手动编码URL参数 private static String urlencode(List<NameValuePair> params) { // ... 实现 URL 编码方法 ... } ``` 在这个例子中,我们创建了一个POST请求,并添加了一个名为"data-raw"的数据项。注意,你需要根据实际情况替换URL和"data-raw"的实际值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值