JAVA-POST请求多个参数

第一种:

用类似GET方式拼接参数,自行动态拼接.格式固定

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
 
public class cs {

    public static void main(String[] args) {
        String result = jsonpost("http://ip:28888/api/getToken", "&username=1&passwd=111111");
        System.out.println(result);
    }
    /**
     * @Description: post 请求
     * @Author: ckx
     * @Date: 2022/11/21 09:00 
     *  args:url
     *  args1 : 参数
     */
    public static String jsonpost(String args, String args1) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(args);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            //设置通用的请求头属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行   否则会抛异常(java.net.ProtocolException: cannot write to a URLConnection if doOutput=false - call setDoOutput(true))
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //获取URLConnection对象对应的输出流并开始发送参数
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            //添加参数
            out.write(args1);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result.toString();
    }
}

第二种:

有的工具类用的NameValuePair这种类型.也不知道是啥玩,大致理解跟Map差不多,K,V结构.加个List泛型就能传多个参数了

package cn.itcast.crawler.test;
 
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
 
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
 
public class HttpPostParamTest {
 
    public static void main(String[] args) throws Exception {
        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
 
        //创建HttpPost对象,设置url访问地址
        HttpPost httpPost = new HttpPost("http://yun.itheima.com/search");
 
        //声明List集合,封装表单中的参数
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        //设置请求地址是:http://yun.itheima.com/search?keys=Java
        params.add(new BasicNameValuePair("keys","Java"));
 
        //创建表单的Entity对象,第一个参数就是封装好的表单数据,第二个参数就是编码
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params,"utf8");
 
        //设置表单的Entity对象到Post请求中
        httpPost.setEntity(formEntity);
 
        CloseableHttpResponse response = null;
        try {
            //使用HttpClient发起请求,获取response
             response = httpClient.execute(httpPost);
 
            //解析响应
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                System.out.println(content.length());
            }
 
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭response
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

第三种:

第二种的变形封装,简便

package com.test;
 
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
 
import java.util.ArrayList;
import java.util.List;
 
public class Test {
    
/**
     *
     * 发送请求
     * @param url 发送的url
     * @param headerMap  请求头参数集合 key参数名 value为参数值
     * @param bodyMap   请求参数集合 key参数名 value为参数值
     */
    public static String sendPost(String url, Map<String,String> headerMap,Map<String,String> bodyMap){
 
        //创建post请求对象
        HttpPost post = new HttpPost(url);
        try {
            //创建参数集合
            List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
            //添加参数
            if (bodyMap!=null){
                for (String str:bodyMap.keySet()
                ) {
                    list.add(new BasicNameValuePair(str, bodyMap.get(str)));
                }
            }
            //把参数放入请求对象,,post发送的参数list,指定格式
            post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
 
 
            if (headerMap!=null){
                for (String str:headerMap.keySet()
                     ) {
                    post.addHeader(str,headerMap.get(str));
                }
            }
 
            CloseableHttpClient client = HttpClients.createDefault();
            //启动执行请求,并获得返回值
            CloseableHttpResponse response = client.execute(post);
            //得到返回的entity对象
            HttpEntity entity = response.getEntity();
            //把实体对象转换为string
            String result = EntityUtils.toString(entity, "UTF-8");
            //返回内容
            return result;
        } catch (Exception e1) {
            e1.printStackTrace();
            return "";
        }
    }
}

你可能感兴趣的:(JAVA,java,servlet,开发语言)