调用远程接口,返回数据

public String httpPost(String urlStr, ArrayList> list){
        URL connect;
        StringBuffer responseData = new StringBuffer();
        try {
            connect =  new URL(urlStr);
            //开启连接
            HttpURLConnection connection = (HttpURLConnection) connect.openConnection();
            /*为连接设置参数*/
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setDefaultUseCaches(false);  //post方法禁用缓存
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0");
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
            JSONArray jsonArray = JSONArray.fromObject(list);
            String str = "str="+jsonArray.toString();
            writer.write(str);
            writer.flush();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            while ((line=reader.readLine()) != null) {
                responseData.append(line);
            }
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseData.toString();
    }


你可能感兴趣的:(编程技术,java,mysql)