java编写接口发送POST请求

public static String interfaceUtil(String path,String params) {
try {
URL url = new URL(path);
//打开和url之间的连
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);//向连接中读取数据
conn.setDoInput(true);//向连接中写入数据
conn.setUseCaches(false);//禁止使用缓存
conn.setInstanceFollowRedirects(true);//自动执行HTTP重定�?
conn.setRequestMethod(“POST”);//请求方式

        //设置通用的请求属
        conn.setRequestProperty("Accept", "application/json"); // 设置接收数据的格�?  
         // 设置发�?�数据的格式   
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");

        // 建立连接
        conn.connect();

        //获取URLConnection对象对应的输出流
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); // utf-8编码  
        out.append(params.toString());  

        //缓冲数据
        out.flush();
        out.close();
     
        //读取响应
        int length = (int) conn.getContentLength();// 获取长度
        //获取URLConnection对象对应的输入流
        InputStream is = conn.getInputStream();
        System.out.println(length);
        if (length != -1) {  
            byte[] data = new byte[length];  
            byte[] temp = new byte[512];  
            int readLen = 0;  
            int destPos = 0;  
            while ((readLen = is.read(temp)) > 0) {  
                System.arraycopy(temp, 0, data, destPos, readLen);  
                destPos += readLen;  
            }  
            String result = new String(data, "UTF-8"); // utf-8编码  
            return result;  
        }  
        //关闭
        is.close();
        conn.disconnect();
        System.out.println("结束");
    } catch (Exception e) {
        e.printStackTrace();
    }
	return  "error"; // 自定义错误信�?  
}

你可能感兴趣的:(java编写接口发送POST请求)