java模拟post请求

利用java模拟post请求,有参数,参数格式为map形式
“`java

public static void post(Integer i,String urlStr, Map<String, String> parameterMap)
        throws IOException {
    URL url = new URL(urlStr);
    HttpURLConnection httpURLConnection = (HttpURLConnection) url
            .openConnection();
    httpURLConnection.setDoInput(true);
    httpURLConnection.setDoOutput(true); // 设置该连接是可以输出的
    httpURLConnection.setRequestMethod("POST"); // 设置请求方式
    httpURLConnection.setRequestProperty("charset", "utf-8");
    System.out.println(httpURLConnection.getURL().toString());
    PrintWriter pw = new PrintWriter(new BufferedOutputStream(
            httpURLConnection.getOutputStream()));
    StringBuffer parameter = new StringBuffer();
    parameter.append("1=1");
    for (Entry<String, String> entry : parameterMap.entrySet()) {
        parameter.append("&" + entry.getKey() + "=" + entry.getValue());
    }
    pw.write(parameter.toString());// 向连接中写数据(相当于发送数据给服务器)
    pw.flush();
    pw.close();
    System.out.println("parameter: " + parameter.toString());
    BufferedReader br = new BufferedReader(new InputStreamReader(
            httpURLConnection.getInputStream(), "utf-8"));
    String line = null;
    StringBuilder sb = new StringBuilder();
    while ((line = br.readLine()) != null) { // 读取数据
        sb.append(line + "\n");
    }
    br.close();
    System.out.println(sb.toString());
}
```

注意:如果用gradle,需要下载个jar包

compile(‘commons-httpclient:commons-httpclient:3.0.1’)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值