一、java后台post请求发送json参数
GET请求向服务器发送的数据,都放在url中,这样在发送请求时不用向请求正文中写入数据。而POST请求在发送时,必须先将发送的数据,写入到请求正文中。
package dw.health;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class App
{
public static JSONObject sendPost(String url,JSONObject jsonParam) throws Exception {
OutputStream out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
HttpURLConnection conn = null;
try {
// 创建url资源
URL url_ = new URL(url);
// 建立http连接
conn = (HttpURLConnection) url_.openConnection();
// 设置传递方式
conn.setRequestMethod("POST");
// 设置允许输入、允许输出
conn.setDoInput(true);
conn.setDoOutput(true);
// 设置不用缓存
conn.setUseCaches(false);
//设置连接超时时间和读取超时时间
conn.setConnectTimeout(30000);
conn.setReadTimeout(10000);
// 转换为字节数组
byte[] data = (jsonParam.toString()).getBytes();
// 设置文件长度
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
// 设置文件类型:
conn.setRequestProperty("contentType", "application/json");
// 开始连接请求
conn.connect();
out = new DataOutputStream(conn.getOutputStream()) ;
// 写入请求的字符串(此时jsonParam数据是放在了请求正文body里)
out.write((jsonParam.toString()).getBytes());
out.flush();
out.close();
// 请求返回的状态
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()){
// System.out.println("连接成功");
// 请求返回的数据
InputStream in1 = conn.getInputStream();
try {
String readLine=new String();
BufferedReader responseReader=new BufferedReader(new InputStreamReader(in1,"UTF-8"));
while((readLine=responseReader.readLine())!=null){
result.append(readLine).append("\n");
}
responseReader.close();
} catch (Exception e1) {
e1.printStackTrace();
}
} else {
System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
}
} catch (Exception e) {
throw new Exception(e);
}finally {
try{
if(out != null){
out.close();
}
if(in != null){
in.close();
}
}catch (IOException ioe){
ioe.printStackTrace();
}
}
return JSONObject.parseObject(result.toString());
}
public static void main( String[] args ) throws Exception {
JSONObject jsonParam = new JSONObject();
jsonParam.put("para1", "para1");
jsonParam.put("para2", "para2");
jsonParam.put("para3", "para3");
String url="servlet请求地址";
JSONObject data = sendPost(url,jsonParam);
System.out.println(data);
}
}
二、通过HttpServletRequest获取post请求中的body内容(未使用注解)
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
String str = "";
String wholeStr = "";
while((str = reader.readLine()) != null){
wholeStr += str;
}
JSONObject param = JSONObject.parseObject(wholeStr);
String para1 = param.getString("para1");
String para2 = param.getString("para2");
String para3 = param.getString("para3");
JSONObject result = new JSONObject();
PrintWriter writer = null;
LinkedHashMap<String, String> hm = new LinkedHashMap<String, String>();
String resp = "";
JSONObject jsonobj = new JSONObject(true);
try {
param.put("para4","para4");
result = param;
resp = result.getString("data");
} catch (Exception e) {
hm.put("errorcode", "1");
hm.put("errortext", e.getMessage());
jsonobj.putAll(hm);
resp = jsonobj.toJSONString();
}
try {
response.setCharacterEncoding("GBK");
writer = response.getWriter();
writer.write(resp);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
writer.close();
}
}