httpURLConnection 请求发起post请求

 

常见请求头,在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  方法方法结束

  用 HttpPost   封装好的组件的话比较直接,但是以下方法需要在另一线程调用,

private void doPost(String s) {
    HttpPost httpPost = new HttpPost(urlAddress + method);
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("sex", s));
    
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);
        
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            String result = EntityUtils.toString(httpResponse.getEntity());
            Log.d("test", result);
        } else {
            Log.d("test","failed");
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

 

posted @ 2023-11-04 11:58  谢双元小号  阅读(1002)  评论(0编辑  收藏  举报