HttpURLConnection POST 请求如何设置参数

clipboard.png 这样设置不知道对不对?我在服务端不知道怎么获取。request.getParam 获得不到。

阅读 23.4k
1 个回答

POST参数需要获取输出流,往输出流里写字节就可以了。给出以下参考代码demo:

//demo
public class ServletMain {

    public static void main(String[] args) {
        TestBean tb=new TestBean("age","25");
        Gson gson=new Gson();
        //传入的参数
        String param=gson.toJson(tb);
        String url="http://localhost:8080/do.htm?type=ajaxRequest";
        String data=sendPostRequest(url,param);
                //请求回来的数据
                System.out.println(data);
    }
    
    public static String sendPostRequest(String url,String param){
        HttpURLConnection httpURLConnection = null;
        OutputStream out = null; //写
        InputStream in = null;   //读
        int responseCode = 0;    //远程主机响应的HTTP状态码
        String result="";
        try{
            URL sendUrl = new URL(url);
            httpURLConnection = (HttpURLConnection)sendUrl.openConnection();
            //post方式请求
            httpURLConnection.setRequestMethod("POST");
            //设置头部信息
            httpURLConnection.setRequestProperty("headerdata", "ceshiyongde");
            //一定要设置 Content-Type 要不然服务端接收不到参数
            httpURLConnection.setRequestProperty("Content-Type", "application/Json; charset=UTF-8");
            //指示应用程序要将数据写入URL连接,其值默认为false(是否传参)
            httpURLConnection.setDoOutput(true);
            //httpURLConnection.setDoInput(true); 
            
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setConnectTimeout(30000); //30秒连接超时
            httpURLConnection.setReadTimeout(30000);    //30秒读取超时
            //获取输出流
            out = httpURLConnection.getOutputStream();
            //输出流里写入POST参数
            out.write(param.getBytes());
            out.flush();
            out.close();
            responseCode = httpURLConnection.getResponseCode();
            BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"UTF-8"));
            result =br.readLine();
        }catch(Exception e) {
            e.printStackTrace();
          
      }
    return result;
      
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题