java编写向接口POST 一个Jason请求,要求 post的方法要单独封装一个类 (有其他类调用post方法,参数最好是json体和链接地址,需要得出返回结果并打印返回信息和http状态码,只打印返回结果和状态码,其他的不能打印出)
import java.io.BufferedReader; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.io.OutputStreamWriter; import java.io.InputStream; import java.io.InputStreamReader; //import java.net.MalformedURLException; import net.sf.json.JSONObject; //import java.io.InputStreamReader; //import java.io.UnsupportedEncodingException; //import java.io.BufferedReader; //import java.io.DataOutputStream; public class confirmSendJson { /** * 发送HttpPost请求 * * @param strURL * 服务地址 * @param params * json字符串,例如: "{ "id":"12345" }" ;其中属性名必须带双引号<br/> * @return 成功:返回json字符串<br/> */ final static String addr_url = "http://xxxx.com/v1/api/payRequest"; final static String params ="{"channelCode": "01"," +""platformCode": "03"," +""tradeNo": "1474878291690"," +""subject": "打赏"," +""payAmount": 1," +""notifyUrl": "http://xxxx.com/v1/test/notify"," +""returnUrl": "http://xxxx.com/v1/test/notify/sync"," +""expire": 300," +""extra": "hello world"," +""openId": "oSlbct45e-fTbFJOtZvZjV5gNKBE"," +""sign": "7BB370F84FD481BC758836BB7919BBEF"}"; public static String post(String addr_url, String params){ String result=""; BufferedReader in = null; OutputStreamWriter out=null; try { //创建连接 URL url = new URL(addr_url); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false);//post不能保存缓存 connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式 connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式 connection.connect(); //POST请求 out = new OutputStreamWriter( connection.getOutputStream(), "UTF-8"); // utf-8编码 out.append(params); out.flush(); out.close(); Map<String,List<String>> map = connection.getHeaderFields(); for (String key : map.keySet()){ System.out.println(key + "------>" +map.get(key)); } //读取响应 in = new BufferedReader( new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送 POST 请求出现异常!"+e); e.printStackTrace(); } //使用finally块来关闭输出流、输入流 finally{ try{ if(out!=null){ out.close(); } if(in!=null){ in.close(); } } catch(IOException ex){ ex.printStackTrace(); } } return result; } public static void main(String[] args) { String result=null; result= post(addr_url, params); System.out.println(result); } }