java发送post请求携带map参数,获取返回值

需要注意的是:有时候post请求也并不是一定会把参数存在map里,放入方法体中;本人在实际操作中,将参数存在map中,放入方法体,执行代码一直报500错误。服务端也没有成功取到存放的参数。之后改成 ?参数=xxx 的格式,才发送请求成功。

import com.alibaba.fastjson.JSON;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;    


public static void main(String[] args) {
        Map map = new HashMap<>();
        map.put("code","SQ");

        String param= JSON.toJSONString(map);
        String url = "http://localhost:8888/MeteoBP/api/rest/web/product/product3d?datetime=20220630000000&type=24";
        String postValue =  sendPost(url, param,Charset.forName("utf-8"));
        System.out.println(postValue);

    }



public static String sendPost(String url, String param, Charset charset)  {
        try {
            URL httpurl = new URL(url);
            //打开和url的连接
            HttpURLConnection httpConn = (HttpURLConnection) httpurl.openConnection();
            //设置通用的请求头属性
            httpConn.setRequestMethod("POST");
            httpConn.setRequestProperty("accept", "*/*");
            httpConn.setRequestProperty("connection", "Keep-Alive");
            httpConn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset.name());
            /*httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; "
                    + "Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");*/

            // 发送POST请求必须设置如下两行   否则会抛异常(java.net.ProtocolException: cannot write to a URLConnection if doOutput=false - call setDoOutput(true))
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);

            httpConn.setUseCaches(false);
            /*httpConn.setRequestMethod("POST");
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset.name());*/
            httpConn.connect();
            OutputStream outputStream = httpConn.getOutputStream();
            PrintWriter out = new PrintWriter(outputStream);
            //print在方法内也是调用的write方法,多了null的判断逻辑
            out.print(param);
            //out.write(param);
            out.flush();
            out.close();
            InputStream inputStream = httpConn.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, charset.name()));
            StringBuffer stringBuffer = new StringBuffer();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }
            String resp = stringBuffer.toString();
            // System.out.println(resp);
            if (stringBuffer != null) {
                try {
                    bufferedReader.close();
                } catch (IOException var18) {
                    var18.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException var17) {
                    var17.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException var17) {
                    var17.printStackTrace();
                }
            }
            return resp;
        }catch (IOException e) {
            throw new RuntimeException(String.format("url:%s,param:%s,message:%s", url, param, e.getMessage()), e);
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java发送 POST 请求携带文件和参数,你可以使用 `java.net.HttpURLConnection` 类来实现。下面是一个示例代码: ```java import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class FileUploadExample { public static void main(String[] args) throws IOException { String url = "http://example.com/upload"; // 请求的URL String filePath = "/path/to/file"; // 文件路径 String paramName = "file"; // 文件参数名 String paramName2 = "param1"; // 其他参数名 String paramValue2 = "value1"; // 其他参数值 File file = new File(filePath); URL requestUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection(); // 设置请求方法为POST connection.setRequestMethod("POST"); connection.setDoOutput(true); // 设置请求头部信息 connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"); try (OutputStream outputStream = connection.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream))) { // 写入文件参数 writer.append("------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n") .append("Content-Disposition: form-data; name=\"" + paramName + "\"; filename=\"" + file.getName() + "\"\r\n") .append("Content-Type: " + HttpURLConnection.guessContentTypeFromName(file.getName()) + "\r\n") .append("\r\n") .flush(); // 写入文件内容 try (InputStream inputStream = new FileInputStream(file)) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); } // 写入其他参数 writer.append("\r\n") .append("------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n") .append("Content-Disposition: form-data; name=\"" + paramName2 + "\"\r\n") .append("\r\n") .append(paramValue2) .append("\r\n") .flush(); // 结束标记 writer.append("------WebKitFormBoundary7MA4YWxkTrZu0gW--\r\n").flush(); } // 发送请求获取响应 int responseCode = connection.getResponseCode(); System.out.println("Response Code: " + responseCode); try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } System.out.println("Response: " + response.toString()); } } } ``` 在上面的示例代码中,我们首先创建了一个 `HttpURLConnection` 对象,并设置请求方法为 POST,然后设置请求头部信息。接下来,我们使用输出流向服务器写入请求体内容,首先是文件参数,然后是文件内容,最后是其他参数发送请求后,我们可以获取响应的状态码和响应内容。 请注意,示例中的边界字符串 `"----WebKitFormBoundary7MA4YWxkTrZu0gW"` 只是一个示例,请根据实际情况修改该字符串。 希望这可以帮助到你!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值