标签:
package com.mytesting; import java.io.DataOutputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import org.apache.commons.io.IOUtils; public class post { public static void main(String[] args) { // TODO Auto-generated method stub doHttpPost("http://172.18.3.27:8031/Activity/GetActivityList","{\"TPID\":123}"); //第一个是请求URL 第二个是body内的参数 } /** * 发送POST请求 * * @param postBody * @return */ public static String doHttpPost(String URL,String postBody) { // System.out.println("发起的数据:" + postBody); byte[] xmlData = postBody.getBytes(); InputStream instr = null; try { URL url = new URL(URL); URLConnection urlCon = url.openConnection(); urlCon.setDoOutput(true); urlCon.setDoInput(true); urlCon.setUseCaches(false); urlCon.setRequestProperty("Content-Type", "application/json"); urlCon.setRequestProperty("User-Agent", "app30007/3F845F3287A3C3F20A04B08C5074FC95/2B80541F-1C28-4FE7-8EEF-4A20D688A984/0/"); urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length)); DataOutputStream printout = new DataOutputStream( urlCon.getOutputStream()); printout.write(xmlData); printout.flush(); printout.close(); instr = urlCon.getInputStream(); byte[] bis = IOUtils.toByteArray(instr); String ResponseString = new String(bis, "UTF-8"); if ((ResponseString == null) || ("".equals(ResponseString.trim()))) { System.out.println("返回空"); } System.out.println("返回数据为:" + ResponseString); return ResponseString; } catch (Exception e) { e.printStackTrace(); return "0"; } finally { try { // out.close(); instr.close(); } catch (Exception ex) { return "0"; } } } }
引入所需的包,有一些额外的包需要下载
标签:
原文地址:http://www.cnblogs.com/demonzyz/p/4453522.html