Java HttpURLConnection POST方式调用接口并携带两个参数
花了挺久的时间,看了好多方式,都不行,搞了好久终于解决,现在把代码贴出来,帮助有需要的人
第一步:写一个调用接口方法
private void updateNotice(String url1, String Message) throws Exception { //设置通用的请求属性 String[] strings = Message.split(","); String json = "{\"id\":\"" + strings[0] + "\",\"copNo\":\"" + strings[1] + "\",\"declareReceipt\":\"正在申报中\",\"declareStatus\":\"2\",\"fileName\":\"CEB621Message" + strings[2] + ".xml\",\"createBy\":\"管理员\"}"; //签名 //规则为id+copno+declarestatus //生成的md5字符串规则 String md5 = strings[0] + strings[1] + "2"; String md5Encode = DigestUtils.md5Hex(md5).toLowerCase(); // Post请求的url,与get不同的是不需要带参数 URL postUrl = new URL(url1); // 打开连接 HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection(); // 设置是否向connection输出,因为这个是post请求,参数要放在 // http正文内,因此需要设为true connection.setDoOutput(true); // Read from the connection. Default is true. connection.setDoInput(true); // 默认是 GET方式 connection.setRequestMethod("POST"); // Post 请求不能使用缓存 connection.setUseCaches(false); //设置本次连接是否自动重定向 connection.setInstanceFollowRedirects(true); // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的 // 意思是正文是urlencoded编码过的form参数 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成, // 要注意的是connection.getOutputStream会隐含的进行connect。 connection.connect(); DataOutputStream out = new DataOutputStream(connection .getOutputStream()); // 正文,正文内容其实跟get的URL中 '? '后的参数字符串一致 String content = "json=" + URLEncoder.encode(json, "UTF-8") + "&sign=" + URLEncoder.encode(md5Encode, "UTF-8"); // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面 out.writeBytes(content); //流用完记得关 out.flush(); out.close(); //获取响应 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); //结束,记得把连接断了 connection.disconnect(); }
第二步:开始调用
public static void main(String[] args) { //修改报文状态及申报信息 String updateNoticeUrl = "http://127.0.0.1/api/updateNotice"; try { m.updateNotice(updateNoticeUrl, map.get(i + "")); } catch (Exception e) { e.printStackTrace(); } }