java模拟post请求

来源:互联网 发布:新浪sae绑定域名 编辑:IT博客网 时间:2019/06/27 21:13

利用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’)

0 0