使用HttpClient往别人提供的接口推送json数据,并获取返回值

控制层,将要推送的json数据进行封装

public void Pushdata() {
		JSONObject json = new JSONObject();
		//此处封装json数据

//调用工具类中的方法,传入url以及json数据进行推送
		try {
			String bd = CommonUtil.sendPut("url", json, "UTF-8");			
			JSONObject object = JSON.parseObject(bd); //获取对方返回的数据
			//String ss = object .getString("data");
		
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		} 
	}

在pom.xml中加入依赖

		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.7</version>
		</dependency>

		<dependency>
			<groupId>com.google.http-client</groupId>
			<artifactId>google-http-client</artifactId>
			<version>1.22.0</version>
		</dependency>

工具类中的数据推送方法

/**
	 * HttpClient 推送数据
	 * 
	 * @param url 接口地址
 	 * @param json 传入的参数 
	 * @return String 
	 */
	public static String sendPut(String url, JSONObject putData, String encoding) throws ParseException, IOException {
		String body = "";
		System.err.println(putData.toJSONString());//打印了一下我推送的json数据
		CloseableHttpResponse response = null;
		CloseableHttpClient client = HttpClients.createDefault();
		
		//向指定资源位置上传内容
		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
		httpPost.setEntity(new StringEntity(JSONObject.toJSONString(putData)));
		try {
			response = client.execute(httpPost);
			System.err.println("status" + response.getStatusLine().getStatusCode());
			
			//通过response中的getEntity()方法获取返回值
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				body = EntityUtils.toString(entity, encoding);
			}   
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
	   	} finally {
			httpPost.abort();
			if (response != null) {
				EntityUtils.consumeQuietly(response.getEntity());
			}
		}

		System.err.println("body:" + body);
		return body;
	}

在这里插入图片描述

Java 通过 HttpClient 调用 Push 接口推送云 API)可以使用以下代码: ```java import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; 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 class PushClient { private static final String PUSH_URL = "https://api.push.com/v2/push"; private static final String APP_KEY = "your app key"; private static final String MASTER_SECRET = "your master secret"; public static void main(String[] args) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(PUSH_URL); // 设置请求头 httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); httpPost.setHeader("Authorization", "Basic " + base64Encode(APP_KEY + ":" + MASTER_SECRET)); // 设置请求参数 List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("platform", "android")); params.add(new BasicNameValuePair("audience", "all")); params.add(new BasicNameValuePair("notification", "{\"alert\":\"Hello, world!\"}")); httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8)); // 发送请求并获取响应 HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity, StandardCharsets.UTF_8); // 处理响应 System.out.println(result); // 关闭连接 httpClient.close(); } private static String base64Encode(String str) { return new String(java.util.Base64.getEncoder().encode(str.getBytes())); } } ``` 其中,`PUSH_URL` 是 Push 接口的 URL,`APP_KEY` 和 `MASTER_SECRET` 是 Push 服务的 App Key 和 Master Secret。通过设置请求头和请求参数,构造 `HttpPost` 请求对象,并发送请求获取响应,最后处理响应即可完成 Push 消息的发送。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值