httpURLConnection 请求发起post请求

发布时间 2023-11-04 12:03:44作者: 卢敏表妹

 

常见请求头,在post请求之 前先了解一下,请求相关的基础

 关于post 请求的方式比get  多了很多配置,其实大致一样,本想将get示例和post写在一起,这个博客功能有时有问题 一直在灰色的编辑框中跳不出去,只能另起一篇博客。

    private void doPost(String s) {
        try {
//            URl构建的是一上地址对象
         URL url =  new URL(UrlAddress);
//         创建一个连接
         HttpURLConnection httpURLConnection =(HttpURLConnection) url.openConnection();
//         由于是post 请求需要配置参数
         httpURLConnection.setDoInput(true);
         httpURLConnection.setDoOutput(true);
//         配置请求头
         httpURLConnection.setRequestMethod("POST");
//         配置请求是否有缓存
         httpURLConnection.setDefaultUseCaches(false);
         HttpURLConnection.setDefaultRequestProperty("Accept-Charset","UTF-8");
         HttpURLConnection.setDefaultRequestProperty("Content-Type","application/x-www-form-urlencoded");
//         配置好了尝试连接准备
         httpURLConnection.connect();
            DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
//            拼接请求参数,比如条件,性别,
           String content = "set="+s;
           outputStream.write(content.getBytes());
           outputStream.flush();
           outputStream.close();
//以下的处理和get 一样了
           if(httpURLConnection.getResponseCode() == 200){
               InputStream is =httpURLConnection.getInputStream();
               BufferedReader br = new BufferedReader(new InputStreamReader(is));
               StringBuffer Sbuffer = new StringBuffer();
               String readLine = "";
               while ((readLine = br.readLine())!=null){
                   Sbuffer.append(readLine);
               }
               is.close();
               br.close();
               httpURLConnection.disconnect();
               Log.d("Text",Sbuffer.toString());   
           }

        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
        }
    } //dopost  方法方法结束