post 调用接口,带入json参数,返回json 代码笔记

	/**
	 * post 调用接口
	 */
	@Override
	public void getinterfaceByYC(XXX base) {
	    String ywbm = base.getxxx();
		String bljd = base.getXX();
		String username = "";
		String password = "";
		
		String url = "http://xxxx";

		byte[] requestBytes;
		String result = "";
		try {
			JSONObject js = new JSONObject();
			js.put("xxx", xxx);
		        js.put("xx", xx);

			String string = js.toString();

			requestBytes = string.getBytes("utf-8");
			HttpClient httpClient = new HttpClient();// 客户端实例化
			PostMethod postMethod = new PostMethod(url);
			// 设置请求头Authorization
			// postMethod.setRequestHeader("Authorization", "Basic " +
			// authorization);
			// 设置请求头 Content-Type
			postMethod.setRequestHeader("Content-Type", "application/json");
			InputStream inputStream = new ByteArrayInputStream(requestBytes, 0,
					requestBytes.length);
			RequestEntity requestEntity = new InputStreamRequestEntity(
					inputStream, requestBytes.length,
					"application/json; charset=utf-8"); // 请求体
			postMethod.setRequestEntity(requestEntity);
			httpClient.executeMethod(postMethod);// 执行请求
			InputStream soapResponseStream = postMethod
					.getResponseBodyAsStream();// 获取返回的流
			byte[] datas = null;
			datas = readInputStream(soapResponseStream);// 从输入流中读取数据
			result = new String(datas, "UTF-8");// 将二进制流转为String
			// 打印返回结果
			System.out.println("result:------" + result);
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} // 将参数转为二进制流
		catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/**
		 * String result = {"aaa":"111","bbb":"222"}
		 *  提取JSON字符串数据
		 */
		
		if (result != null && !"".equals(result)) {
			result = "[" + result + "]";
			JSONArray jsonarray = JSONArray.fromObject(result);
			String jsonString = jsonarray.getString(0);
			Map deviceMap = new HashMap<>();
			Gson gson = new Gson();
			deviceMap = gson.fromJson(jsonString, deviceMap.getClass());
			System.out.println(deviceMap.get("aaa"));
		}
		System.out.println(result);
	}


	/**
	 * 从输入流中读取数据
	 */
	private byte[] readInputStream(InputStream soapResponseStream) {
		byte[] buffer = new byte[1024];
		int len = -1;
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		try {
			while ((len = soapResponseStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, len);
			}
			outputStream.close();
			soapResponseStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return outputStream.toByteArray();
	}

被调用的接口 写法

   @ResponseBody
    @PostMapping("xxxx")
    public JSONObject update_start(@RequestBody JSONObject jsonObject){
        System.out.println("1111111");
        System.out.println(jsonObject.toString());

        JSONObject json = new JSONObject();
        json.put("aaa","111");
        json.put("bbb","222");
        System.out.println(json.toString());
        return json;
    }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
可以使用Java提供的HttpURLConnection或者Apache HttpClient库来实现POST请求提交JSON参数。 使用HttpURLConnection实现POST请求提交JSON参数的示例代码如下: ```java import java.net.HttpURLConnection; import java.net.URL; import java.io.OutputStream; public class HttpPostJson { public static void main(String[] args) throws Exception { String url = "http://example.com/api"; String json = "{\"username\":\"test\",\"password\":\"123456\"}"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 添加请求头 con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); // 发送POST请求 con.setDoOutput(true); OutputStream os = con.getOutputStream(); os.write(json.getBytes("UTF-8")); os.flush(); os.close(); // 获取返回结果 int responseCode = con.getResponseCode(); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 打印返回结果 System.out.println(response.toString()); } } ``` 使用Apache HttpClient库实现POST请求提交JSON参数的示例代码如下: ```java import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.HttpResponse; import java.io.BufferedReader; import java.io.InputStreamReader; public class HttpPostJson { public static void main(String[] args) throws Exception { String url = "http://example.com/api"; String json = "{\"username\":\"test\",\"password\":\"123456\"}"; HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost request = new HttpPost(url); // 设置请求头 request.setHeader("Content-Type", "application/json"); // 设置请求参数 StringEntity params = new StringEntity(json); request.setEntity(params); // 发送POST请求 HttpResponse response = httpClient.execute(request); // 获取返回结果 BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } // 打印返回结果 System.out.println(result.toString()); } } ``` 以上示例代码仅供参考,实际使用时需要根据自己的需求进行修改。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值