HttpConnection POST传递JSON对象

//工具类

public class HttpConnectionUtils {
   
    public static String httpPost(String urlStr,String data) throws Exception {    
        String lines=null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", 
                    "application/json"); 
            //链接地址 
            conn.connect(); 
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); 
            //发送参数 
            writer.write(data); 
            //清理当前编辑器的左右缓冲区,并使缓冲区数据写入基础流 
            writer.flush();
            if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
                BufferedReader reader = new BufferedReader(new InputStreamReader(   
                        conn.getInputStream()));   
                lines =reader.readLine();//读取请求结果 
            } else {
                System.out.println(conn.getResponseMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lines;
    }
}

//调用方法

String data=JSONObject.toJSON(lists).toString();
            HttpConnectionUtils.httpPost(REST_URL+"/memberLabel/insert", data);

 

alibaba.fastJSON  lists参数为ArrayList();当然可以是其它集合类或者Map

 

你可能感兴趣的:(J2EE)