java调用代码
运行结果:可以调用成功
云数据库端,插入的是一条空数据,参数没有传过去是吗
但为什么参数没有传递过去呢?求各位大佬帮帮小弟,万分感谢!
微信开放文档说明:
你用post应该用body传参,你这附加在url的query string所以接收不到啊,参考这个
import lombok.Data;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
public class Test05 {
@Data
static class Param {
private String htbh;
private String chuzf;
private String chenzf;
}
public static void main(String[] args) {
final RestTemplate restTemplate = new RestTemplate();
final Map map = restTemplate.postForObject("https://api.weixin.qq.com/tcb/invokecloudfunction?access_token={access_token}&env={env}&name={name}",
new Param(),
Map.class,
"access_token", "env", "name"
);
System.out.println(map);
}
}
虽然 HttpUrlConnection这个java内置的网络连接确实可以发送post请求,但是由于使用比较繁琐,还是建议使用 apache的 httpclient或者okhttp或者spring内置的resttemplate。
不过如果确实想用java内置的这个类的话,你可以这样发送post请求,代码仅做参考
private String sendPostRequest(String reqUrl, String jsonData) throws IOException {
StringBuilder stringBuffer = new StringBuilder();
URL url = new URL(reqUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方式
connection.setRequestMethod("POST");
// 设置是否向HttpURLConnection输出
connection.setDoOutput(true);
// 设置是否从httpUrlConnection读入
connection.setDoInput(true);
// 设置是否使用缓存
connection.setUseCaches(false);
//设置参数类型是json格式
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
connection.connect();
BufferedWriter writer = null;
BufferedReader reader = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write(jsonData);
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
//定义 BufferedReader输入流来读取URL的响应
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
stringBuffer.append(line);
}
}
} finally {
if (writer != null) {
writer.close();
}
if (reader != null) {
reader.close();
}
}
return stringBuffer.toString();
}
哪里有那么难啊,就算是繁琐,也没有多复杂的;
post方式,不是放在url里面,不是直接拼接;
简单方便,把参数放在输出里面即可:
conn.getOutputStream().write(param
);